Forum begins after the advertisement:


[Part 16] Mouse-input for aiming weapons (vector-targeted weapons)

Home Forums Video Game Tutorial Series Creating a Rogue-like Shoot-em Up in Unity [Part 16] Mouse-input for aiming weapons (vector-targeted weapons)

Viewing 2 posts - 1 through 2 (of 2 total)
  • Author
    Posts
  • #13539
    Narkka
    Participant

    Hello! I was wondering if there was a way to implement mouse cursor movement to aim weapons, similar to how HoloCure does. If possible, could there be a button to toggle to switch between the mode?

    #13540
    Terence
    Keymaster

    Hi Narkka, the feature you are looking for is called vector-targetting. To implement this on all projectile weapons, you’ll just need to replace the GetSpawnAngle() function shared in Part 15’s ProjectileWeapon.cs script with the following:

        // Gets which direction the projectile should face when spawning.
        protected virtual float GetSpawnAngle()
        {
            Vector2 dir = (Vector2)Input.mousePosition - transform.position;
            return Mathf.Atan2(movement.lastMovedVector.y, movement.lastMovedVector.x) * Mathf.Rad2Deg;
            return Mathf.Atan2(dir.y, dir.x) * Mathf.Rad2Deg;
        }

    If you want to implement this on only a specific weapon / weapons, you will need to extend ProjectileWeapon and override GetSpawnAngle(). Something like this:

    public class VectorProjectileWeapon : ProjectileWeapon
    {
        protected override float GetSpawnAngle()
        {
            Vector2 dir = (Vector2)Input.mousePosition - transform.position;
            return Mathf.Atan2(dir.y, dir.x) * Mathf.Rad2Deg;
        }    
    }

    I hope this makes sense! Basically, we just need to compute a direction vector based on the mouse position of the user. If you want to learn more about the mathematics behind this, you can check out this article: https://blog.terresquall.com/2020/01/vector-math-for-polar-movement-in-2d-games-unity/

Viewing 2 posts - 1 through 2 (of 2 total)
  • You must be logged in to reply to this topic.

Go to Login Page →


Advertisement below: