Reputation:
I have a 2d object that drops when I click the mouse button, and the object moves along the x-axis just fine. But it's not moving according to my mouse pointer's x-coordinate, and when I hit the mouse button it does not drop the object at the position where the mouse pointer is located. I want to fix this issue for the object's movement along the x-axis.
Code:
public class Mouse : MonoBehaviour {
Rigidbody2D body;
float mousePosInBlocks;
void Start () {
body = GetComponent<Rigidbody2D> ();
}
void Update () {
if (Input.GetMouseButtonDown (0)) {
body.isKinematic = false;
}
Vector3 ballPos = new Vector3 (0f, this.transform.position.y, 0f);
mousePosInBlocks = Input.mousePosition.x / Screen.width * 4;
//restrict the position not outside
ballPos.x = Mathf.Clamp (mousePosInBlocks, -2.65f, 2.65f);
this.transform.position = ballPos;
}
}
Upvotes: 1
Views: 685
Reputation: 2943
To make object align with the cursor, use camera.ScreenToWorldPoint
function instead of dividing mouse position by Screen.width. Simply simply dividing by screen width is incorrect, since screen position may also have offset if game window is not exactly in the screen corner. Some more info here: http://docs.unity3d.com/ScriptReference/Camera.ScreenToWorldPoint.html
Also, just an advice - when using rigidbodies, do not use transform.position
, use rigidbody.position
instead, it is much more efficient. So the code would look like this:
using UnityEngine;
using System.Collections;
[RequireComponent(typeof(Rigidbody2D))]
public class Mouse : MonoBehaviour {
Rigidbody2D body;
float mousePosInBlocks;
void Start () {
body = GetComponent<Rigidbody2D> ();
}
void Update () {
if (Input.GetMouseButtonDown (0)) {
body.isKinematic = false;
}
Vector3 ballPos = new Vector3 (0f, this.transform.position.y, 0f);
mousePosInBlocks = Camera.main.ScreenToWorldPoint(Input.mousePosition).x;
//restrict the position not outside
ballPos.x = Mathf.Clamp (mousePosInBlocks, -2.65f, 2.65f);
body.position = ballPos;
}
}
Upvotes: 2