Unity3d mouse

I'm making a cannonball game. here's a shortcode where i calculate 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 balls are at an angle (0,0,0). But when the angle changes, I cannot shoot in the right direction.

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

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

I want to throw the ball in any direction. But suppose it is equal to 0 corners and rolls accordingly.

+3


source to share


1 answer


The usage Camera.ScreenToWorldPoint

is incorrect in this situation.

You have to use raycasting against the plane. Here's a demo without unnecessary math:

raycasting mouse position against a plane

Raycasting gives you the advantage that you don't have to guess how deeply the user (coordinate z

) clicked .



Here's a simple implementation:

/// <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");
}

      


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

+4


source







All Articles