- Home /
Other
How to make an object point at the cursor
How can I maek an object(a flashlight in my case) point at the cursor all the time
@alucardj - I did a search to close this as a dup, but none of the links I tried on the first page yielded a viable answer or they involved Raycasting.
I closed this not as a duplicate but as a write-my-code question. There is no detailed information (2D,3D,view perspective), and there is no indication the OP has read or implemented anything to try and solve the problem themselves.
Answer by robertbu · May 03, 2014 at 09:23 PM
A cursor is 2D, so it's world position depends on whatever distance from the camera you want to use when you translate Screen coordinates to World coordinates. Here is a bit of code that will look at the cursor. Values for 'factor' below 1.0 will cause the object look towards the camera. Values greater than 1.0 will cause the object to look away from the camera. Experiment with different values for 'factor' to get the angle of rotation you want.
#pragma strict
var factor = 0.7;
function Update() {
var dist = (transform.position.z - Camera.main.transform.position.z) * factor;
var pos = Input.mousePosition;
pos.z = dist;
pos = Camera.main.ScreenToWorldPoint(pos);
transform.LookAt(pos);
}
Note if the camera moves or is not axis aligned, you'll want to change line 6 to:
var dist = Vector3.Distance(transform.position, Camera.main.transform.position) * factor;
Follow this Question
Related Questions
Left Click Script Problems 1 Answer
error CS8025: Parsing error 1 Answer
C# Track Mouse Cursor Movement Speed 2 Answers
Distribute terrain in zones 3 Answers
The name 'Joystick' does not denote a valid type ('not found') 2 Answers