#Turret not shooting to mouse position.
1 messages · Page 1 of 1 (latest)
I mean wihtout seeing code nobody can really say anything but I will say this - it looks like your turret is correctly aiming directly at the direction the mouse is pointing, you're just not accounting for the fact that it's elevated off the ground.
Basically your code is aiming perfectly as if the turret was on the ground and the target was on the ground.
So you're simply not accounting for the fact that the turret is a bit elevated
this is so strange but you are right
if I remove the layer off, it shoots straight
but I put the layer for the environment, so that bullets when collide with terrain or static objects they die
We won't know how the layer might affect your shooting direction logic. You should show the code if you want us to be able to help
this is really a logical error in your code. Your code is assuming you want to:
- find the point on the ground your mouse is hovering over
- aim the turret in that direction
- fire
What you really want to do is:
- Find the point on the imaginary plane at the level of the turret's height the mouse is hovering over
- aim the turret in that direction
- fire
The solution is to use Plane.Raycast with an appropriately crafted Plane (at the gun's height) to determine the mouse world position
that part sounds unrelated to the targeting part
private void AimTurretAtMouse()
{
if (turretRoot == null || _cam == null) return;
Vector2 mousePosition = Mouse.current != null ? Mouse.current.position.ReadValue() : Vector2.zero;
Ray ray = _cam.ScreenPointToRay(mousePosition);
Vector3 worldPoint;
if (Physics.Raycast(ray, out RaycastHit hit, 300f, targetLayer))
{
worldPoint = hit.point;
}
else
{
Plane groundPlane = new Plane(Vector3.up, turretRoot.position);
groundPlane.Raycast(ray, out float enter);
worldPoint = ray.GetPoint(enter);
}
Vector3 flatDir = worldPoint - turretRoot.position;
flatDir.y = 0f;
if (flatDir.sqrMagnitude < 0.001f) return;
Quaternion targetRot = Quaternion.LookRotation(flatDir);
turretRoot.rotation = Quaternion.Slerp(
turretRoot.rotation,
targetRot,
Time.deltaTime * rotationSpeed
);
}
This is my code to aim
Yeah so this is your problem:
if (Physics.Raycast(ray, out RaycastHit hit, 300f, targetLayer))
you're doing a physics cast , which will hit the ground
your else block is doing it correctly with a Plane at the correct height
that's why it works when you break the layer mask
assuming turretRoot.position is at the correct height that is