- Home /
Question by
JerryVonJingles · Jun 08, 2015 at 08:46 AM ·
rotationmovementmouseposition
2D click movement not functtioning properly
I'm attempting to make a system in my game in which the player rotates towards the position where the mouse has clicked and then moves towards that position. The script causes the player to rotate properly, but the movement always goes up and to the right in a diagonal (+x and +y direction). Here is the code:
public float speed;
void Update () {
if (Input.GetMouseButton(0)) {
Vector3 mousePos = new Vector3(Input.mousePosition.x, Input.mousePosition.y, 10);
Vector3 lookPos = Camera.main.ScreenToWorldPoint(mousePos);
lookPos = lookPos - transform.position;
float angle = Mathf.Atan2(lookPos.y, lookPos.x) * Mathf.Rad2Deg;
transform.rotation = Quaternion.AngleAxis(angle, Vector3.forward);
transform.position = Vector2.MoveTowards(new Vector2(transform.position.x, transform.position.y), mousePos, speed * Time.deltaTime);
}
}
note: I plan on changing this to touch functionality for phones, would that be easy enough?
Comment
After more testing, another thing to note is that if I click far enough away from my sprite it can "overpower" the diagonal force.