I need help writing a simple script for making an object face the mouse in 2D.

I’ve spent the last 3 days trying to get a simple sprite to face the mouse wherever I put it on the screen, and so far I’ve crashed my computer twice and have gone to bed angry three times, so I finally thought I needed to ask the forums about this. I’m using C#, in monodevelop, and have so far scripted the object to move around, and have put in placeholder entries for some future items, but I need the object to face it’s front side toward my mouse’s location on the screen every frame. I’m rotating around the z axis, y is vertical, x is horizontal. I’m sure this is extremely simple to complete, but I’ve scoured the internet to no avail, so any help is welcome.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class LRmovement : MonoBehaviour {
	public int HP;
	public GameObject Controller;
	public GameObject Cannon;
	public float Speed;
	public Vector3 mousePosition;
	public float targetDistance;

	void Start () 


	void Update () 

		if (Input.GetKey (KeyCode.W))
			transform.position += Vector3.up * Speed * Time.deltaTime;
		if (Input.GetKey (KeyCode.A))
			transform.position += Vector3.left * Speed * Time.deltaTime;
		if (Input.GetKey (KeyCode.S))
			transform.position += Vector3.down * Speed * Time.deltaTime;
		if (Input.GetKey (KeyCode.D))
			transform.position += Vector3.right * Speed * Time.deltaTime;
		mousePosition = Input.mousePosition;

	void LateUpdate ()

		mousePosition = Camera.main.ScreenToWorldPoint (mousePosition);
		mousePosition.z = targetDistance;

this should work - place it inside your update:

        mousePosition = Input.mousePosition;            
        mousePosition = Camera.main.ScreenToWorldPoint(mousePosition);
        Quaternion rot = Quaternion.LookRotation(transform.position - mousePosition, Vector3.forward );
        transform.rotation = rot;   
        transform.eulerAngles = new Vector3(0, 0,transform.eulerAngles.z); 

I didn’t write this myself, I found it here, the second post down:


This question was asked more than a year ago still I will upload this answer for anyone facing similar problem . I was able to put together this script for a top down 3d game it should work the same for 2d games in the x-z plane

`public Vector3 mousePos,lookPos;

void Update () {

	mousePos = new Vector3(Input.mousePosition.x, Input.mousePosition.y, 10);

    lookPos = Camera.main.ScreenToWorldPoint(mousePos);

	lookPos = transform.position-lookPos;

	float angle = Mathf.Atan2(lookPos.z, lookPos.x) * Mathf.Rad2Deg;

	transform.rotation = Quaternion.AngleAxis(angle, Vector3.down);