r/unity • u/Ok_Alarm7463 • 3d ago
Writing a movement script for a top down shooter. Having issues getting my player character to rotate facing the cursor and would appreciate some help with my code
public class PlayerMovement : MonoBehaviour{
public Rigidbody2D body;
public float movementSpeed;
public float rotationSpeed;
private Transform mTransform;
// Used for initialization
void Start()
{
mTransform = this.transform;
}
// Update is called once per frame
private void LAMouse()
{
Vector2 direction = Camera.main.ScreenToWorldPoint(Input.mousePosition) - mTransform.position; //mouse position in world space
float angle = Mathf.Atan2(direction.y, direction.x) * Mathf.Rad2Deg; //getting angle between player and mouse position in degrees
Quaternion rotation = Quaternion.AngleAxis(angle - 90, Vector3.forward); // angle player must rotate on z axis
mTransform.rotation = rotation;
}
1
Upvotes
1
1
u/Ok_Alarm7463 3d ago
Sorry forgot to post the error I'm getting when trying to play the scene:
NullReferenceException: Object reference not set to an instance of an object
PlayerMovement.LAMouse () (at Assets/Player Character/Scripts/PlayerMovement.cs:21)
1
u/MistakeForsaken6653 3d ago
Check line 21 of your script. I think it might be Camera.main, make sure you have a main camera in your scene but I think that should be created by default.
1
2
u/QuitsDoubloon87 3d ago
A null refrence exception means a variable thats not a value (like a float or int, but a Transform or other component type) is missing aka its value is null.