- Home /
2D Sprite rotate relative to mouse snapping incorrectly.
Hello all!
I'm in a little bit of a pickle, what I'm wanting to do is make my sprite rotate accordingly to the direction it's heading. Right now, it seems to just rotate on some weird 360 axis and snap inappropriately.
Here's a video to better describe my problem. I'm trying to make it work like Game Maker orients a sprite with rotation.
Here is my current code for said Unity script.
using UnityEngine;
using System.Collections;
public class PawnPlane : MonoBehaviour {
private Vector3 mousePosition;
private Vector3 mouseRotation;
public float moveSpeed = 1.0f;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
// if (Input.GetMouseButton(1))
{
mousePosition = Input.mousePosition;
mousePosition = Camera.main.ScreenToWorldPoint(mousePosition);
transform.position += new Vector3(mousePosition.x,mousePosition.y,0) * 1.0f * Time.deltaTime;
Vector3 moveDirection = gameObject.transform.position;
float angle = Mathf.Atan2(moveDirection.y, moveDirection.x) * Mathf.Rad2Deg;
transform.rotation = Quaternion.AngleAxis(angle, Vector3.forward);
}
}
}
Any help would greatly be appreciated!
Thanks
Comment
Answer by robertbu · Aug 13, 2014 at 03:43 PM
Your main issue is the calculation of 'moveDirection'. You need to subtract the current position from the mouse position to get a direction. But you also have the same issue with your move direction. You are using a world position as a direction. Try this instead:
using UnityEngine;
using System.Collections;
public class PawnPlane : MonoBehaviour {
public float moveSpeed = 1.0f;
void Update () {
Vector3 mousePosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
Vector3 moveDirection = (mousePosition - transform.position).normalized;
float angle = Mathf.Atan2(moveDirection.y, moveDirection.x) * Mathf.Rad2Deg;
transform.rotation = Quaternion.AngleAxis(angle, Vector3.forward);
transform.position += moveDirection * moveSpeed * Time.deltaTime;
}
}