3

I am making cannonball shooter game. here's a short code where I am calculating the aiming direction.

            Vector3 mousePos = Input.mousePosition;
            mousePos.z = thisTransform.position.z - camTransform.position.z;
            mousePos = mainCamera.ScreenToWorldPoint (mousePos);

            Vector3 force = mousePos - thisTransform.position;
            force.z = force.magnitude;

This works when both ball and at angle (0,0,0). But when the angle changes, I am not able to shoot at right direction.

Suppose both ball and camera are looking at 45 degrees on right side, the same code doesn't work.

The current code assumes both are at angle (0,0,0). So in the above mentioned case, the throwing direction is always wrong.

I want to throw the ball in whatever direction it is. But assume it as 0 angle and throw accordingly.

Krishna Kumar
  • 187
  • 1
  • 17

1 Answers1

7

Using Camera.ScreenToWorldPoint is wrong in this situation.

You should be using raycasting against a plane. Here's a demonstration without unnecesary math:

raycasting mouse position against a plane

Raycasting gives you the advantage, that you don't have to guess how "deep" did the user click (the z coordinate).

Here's a simple implementation of the above:

/// <summary>
/// Gets the 3D position of where the mouse cursor is pointing on a 3D plane that is
/// on the axis of front/back and up/down of this transform.
/// Throws an UnityException when the mouse is not pointing towards the plane.
/// </summary>
/// <returns>The 3d mouse position</returns>
Vector3 GetMousePositionInPlaneOfLauncher () {
    Plane p = new Plane(transform.right, transform.position);
    Ray r = Camera.main.ScreenPointToRay(Input.mousePosition);
    float d;
    if(p.Raycast(r, out d)) {
        Vector3 v = r.GetPoint(d);
        return v;
    }

    throw new UnityException("Mouse position ray not intersecting launcher plane");
}

Demonstation: https://github.com/chanibal/Very-Generic-Missle-Command

Krzysztof Bociurko
  • 4,575
  • 2
  • 26
  • 44
  • Great work! But is it necessary to create a plane each time I want to calculate mouse position? Yes, please you can upload a playable demo for all. – Krishna Kumar Apr 21 '15 at 04:37
  • Sorry, didn't notice your question about the plane: it is not necessary, but is so cheap that you shouldn't bother with it. It's just a math construct, not much more complex than a vector. Plus if it's recalculated each frame, then you can move the plane easily. – Krzysztof Bociurko Sep 03 '15 at 11:25
  • for me, this always returns an exception. – person the human Jun 24 '20 at 22:09
  • @personthehuman, are you sure that the mouse pointer is on the plane? Perhaps you have to move the camera or the GameObject that has this script attached? Check out the demo project if unsure on how to use the script. – Krzysztof Bociurko Jun 25 '20 at 12:34