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;
}
}