- Home /
Object "Look at" Mouse Z Axis
All I'm trying to do, is to get an object to rotate on it's Z axis to "look at" the current mouse position. The camera is orthographic and the object in question does not need to move or rotate in any other way. This camera does not move either.
I need this as an aim mechanic for a Bust-a-move style game project.
What is the easiest way to do this? Every script I've attempted to use has thrown errors for me.
Answer by Tomer-Barkan · Dec 01, 2013 at 05:55 AM
Attach this script to the object you want to rotate:
public class MouseRotator : MonoBehaviour {
public void Update() {
Vector3 mousePositionInWorld = Camera.main.ScreenToWorldPoint(Input.mousePosition);
Vector3 toMousePosition = mousePositionInWorld - transform.position;
transform.up = toMousePosition;
}
}
The first line calculates the world position of the mouse pointer. The second line calculates the vector that points from the object's position to the mouse's position. The third line sets the object's up
direction, so that it points to from the object to the mouse, causing the object to rotate.
It's throwing the following error. Do I need to assign the camera, somehow?
Assets/Lookat$$anonymous$$ouse2.cs(13,60): error CS1061: Type
UnityEngine.Camera' does not contain a definition for
ScreenToWorldPosition' and no extension methodScreenToWorldPosition' of type
UnityEngine.Camera' could be found (are you missing a using directive or an assembly reference?)
$$anonymous$$y Typo, it's ScreenToWorldPoint, not ScreenToWorldPosition. Updated answer.
Good to hear. Please remember in Unity Answers you should accept the answers that solved your problem (clicking the check icon under the vote up/vote down to the left of the answer)
Good luck.
Your answer
Follow this Question
Related Questions
The name 'Joystick' does not denote a valid type ('not found') 2 Answers
Selecting scene for your main menu 1 Answer
Mouse Look Adapt 1 Answer
Aim Assist Script Problems 0 Answers
MouseLook script that points +Y at mouse and rotates on Z 1 Answer