#Turret not shooting to mouse position.

1 messages · Page 1 of 1 (latest)

idle cairn
#

Hi,

So I've been trying to configure my mech to shoot at the current position of my mouse, but apparently it doesnt like to do that.

Rewrote the code a few times because thought maybe I did a mistake, even put it through AI. but apparently its just doing this...

Any thoughts?

spice goblet
#

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

idle cairn
#

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

craggy elm
spice goblet
#

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

spice goblet
idle cairn
#

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

spice goblet
#

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