0
\$\begingroup\$

My new prototype is a top down shooting game, the player aims with the mouse and fires projectiles towards the mouse position, this works fine, when the player is standing still.

When the player moves, the bullets will no longer hit where the mouse is, because the mouse also moves when the player moves obviously. Anyhow ive seen other games still have accurate mouse aim even when the player is moving so there should be some trigonometry wizarddry I can leverage to fix this issue.

Can someone help me out?

Thanks.

My code:

    public void Move(float vertical, float horizontal)
{
    // Calculate movement direction based on camera's forward direction
    _move = (vertical * _cam.forward + horizontal * _cam.right).normalized;

    _cc.Move(_move * _stats.Speed * Time.deltaTime);

    // Debug
    speed = _cc.velocity.magnitude;
}

public void Attack()
{
    _groundPos = transform.position;
    _groundPos.y = 0.02f;

    Vector3 mouseWorldPos = GetMousePosition();
    mouseWorldPos.y = 0.02f;

    Vector3 dirToMouse = (mouseWorldPos - _groundPos).normalized;

    PlayerParticles.Instance.Emit(_stats.Weapon, dirToMouse);
}

private Vector3 GetMousePosition()
{
    Plane playerPlane = new Plane(Vector3.up, transform.position);

    Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);

    if (playerPlane.Raycast(ray, out float hitdist))
    {
        return ray.GetPoint(hitdist);
    }
    else return Vector3.zero;
}

A video of the problem, when the player moves the aiming no longer works: video

\$\endgroup\$
2
  • 1
    \$\begingroup\$ One possibility is to add the player's velocity to the bullets' velocity, so that they don't fall behind. This might not be the behavior you want, however. Can you share a video of a game where the aiming works the way that you want? \$\endgroup\$
    – Kevin
    Apr 13 at 0:13
  • \$\begingroup\$ The video is unavailable, can you provide a different source? \$\endgroup\$
    – liggiorgio
    Apr 14 at 10:13

0

You must log in to answer this question.

Browse other questions tagged .