zack_falcon
zack_falcon

Reputation: 4376

Unity - Trying to move cube to mouse position - cube moves in wrong direction

I'm trying to make a simple game where a cube chases the mouse when the player presses the mouse button down.

Here's my code so far:

public class PlayerCubeController : MonoBehaviour {

    public float speed = 1.0f;
    Vector3 targetPos = new Vector3();

    void Start () {
        speed = speed * 0.01f;
    }

    void Update () {
        if (Input.GetMouseButtonDown (0)) {
            Debug.Log (Input.mousePosition);
            targetPos = Input.mousePosition;
            targetPos.z = 0;

        } else if (Input.GetMouseButtonUp (0)) {
            targetPos = transform.position;
        }

        transform.position = Vector3.Lerp (transform.position, targetPos, speed * Time.deltaTime);
    }
}

Unfortunately, the cube never goes in the direction of the mouse; I can have the mouse in the bottom left of the screen, but the cube will still go to the upper right.

Strangely if I put the mouse in the left side of the screen, the cube will go straight up.

Can anyone tell me where I went wrong?

Upvotes: 1

Views: 1183

Answers (2)

Hellium
Hellium

Reputation: 7346

Your problem is simple : Input.mousePosition defines the mouse position in screen coordinates (from (0,0) to (1920,1080) for example). If you want to get a 3d point from your mouse position, you have an additional step. I see two possibilities :


Use Camera.main.ScreenToWorldPoint and specify by hand the distance you want from your camera :

 var v = Input.mousePosition;
 v.z = 10.0;
 v = Camera.main.ScreenToWorldPoint(v);
 // Move your cube to v

Documentation : https://docs.unity3d.com/ScriptReference/Camera.ScreenToWorldPoint.html


Or use a raycast to get the point on your ground for example using Camera.main.ScreenPointToRay:

    Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
    RaycastHit hit;

    if (Physics.Raycast(ray, out hit, 100))
        // Move your cube to hit.point

Documentation : https://docs.unity3d.com/ScriptReference/Camera.ScreenPointToRay.html

Upvotes: 3

K Scandrett
K Scandrett

Reputation: 16540

In a nutshell you need to convert from screen to world co-ordinates. Here's an example

https://docs.unity3d.com/ScriptReference/Camera.ScreenToWorldPoint.html

Something along the lines of:

 Vector3 mouseP = Input.mousePosition;
 mouseP.z = 10.0;
 Vector3 worldP = Camera.main.ScreenToWorldPoint(mouseP);

Upvotes: 2

Related Questions