- Home /
Rotating object towards mouse point
Same question as here but had to make new post because I couldnt comment/edit my post...
So, I need a turret to point to where my mouse points on the screen.
var gm : GameObject;
function Update () {
var vec3 = Vector3(transform.position.x,transform.position.y,0.2f);
var hPlane: Plane = new Plane(vec3, Vector3.right);
var ray: Ray = Camera.main.ScreenPointToRay (Input.mousePosition);
var dist: float = 0;
if (hPlane.Raycast(ray, dist)){
var hitPt = ray.GetPoint(dist);
transform.LookAt(hitPt);
gm.transform.position = hitPt;
}
}
It works but it has some weird behaviours like the cube that is where the mouse and turret points at is below ground when it is in front of the car and on top of the ground when behind, also it moves weirdly when driving. Any help?
Test the game here.
Answer by whydoidoit · Jul 05, 2012 at 01:25 PM
So your problem is that you aren't getting the hit point - just always using the distance:
var gm : GameObject;
function Update () {
var vec3 = Vector3(transform.position.x,transform.position.y,0.2f);
var hPlane: Plane = new Plane(vec3, Vector3.right);
var ray: Ray = Camera.main.ScreenPointToRay (Input.mousePosition);
var dist: float = 0;
var hit : RaycastHit;
if (hPlane.Raycast(ray, hit, 1000)){
transform.LookAt(hit.point);
gm.transform.position = hit.point;
}
}
There's a bug in this code which has been carried through from the example in the original post. The parameters to create the plane were back to front. The line should be... var hPlane: Plane = new Plane(Vector3.up, vec3);
Your answer
Follow this Question
Related Questions
Camera rotation around player while following. 6 Answers
make turret point where mouse points 3 Answers
Camera Rotate to mouse position -2 Answers
Is There An OnMouseStop? 0 Answers