- Home /
Need help with Transform.LookAt
I'm using Transform.LookAt and the mouse position to rotate the character and shoot from it's forward vector. However, the projectiles are off just a little depending where my cursor is. In certain spots they lineup and others they don't.
The spawnpoint for the projectiles is a child object of the player. All the child objects' rotations are exactly the same (0,0,0). The parent object is perpendicular to the terrain. The forward vector of the spawn point and all the other objects line up perfectly to the projectiles, so I don't think it's a problem with the way the projectiles are spawning. Any suggestions?
RaycastHit hit;
var ray = Camera.main.ScreenPointToRay(Input.mousePosition);
Vector3 newVector3;
if (Physics.Raycast(ray, out hit))
{
newVector3 = new Vector3(hit.point.x, transform.position.y, hit.point.z);
player.transform.LookAt(newVector3);
}
Answer by FlaSh-G · Sep 06, 2017 at 10:19 AM
It's due to the 3D nature of the hit point change you do. If your camera angle would be more flat, you could observe the effect even better.
The noticeable offset (marked in red) comes from the vertical offset to hit.point
you do by setting the y coordinate to transform.position.y
.
To solve this problem, you could do a Plane.Raycast rather than a Physics.Raycast. This would look like this:
The code would be something like this:
var plane = new Plane(Vector3.up, player.transform.position + Vector3.up);
float dist;
if(plane.Raycast(ray, out dist))
{
var point = ray.GetPoint(dist);
player.transform.LookAt(point);
}
Your answer
Follow this Question
Related Questions
shoot bullet on a moving gameobject 0 Answers
transform.lookat snaping direction 0 Answers
Bullet Rotation faces wrong direction 2 Answers
Problem with Shooting Accuracy 0 Answers