# Top down character attack towards mouse position

I’m working on a top down action game with melee combat and I’m having trouble figuring out a part of it. Currently I have it where the character aims towards the mouse at all times, and when they attack will also attack in that direction. For the players movement I’m getting a normalized vector2 and multiplying that by a speed variable to move their rigidbody2D like so:

``````myRB.velocity = new Vector2(controlVector.x * moveSpeed, controlVector.y * moveSpeed);
``````

Now I would also like the basically use this same method to move them in the direction they’re attacking. To get a normalized value for the direction, I’m using this method and then basically doing the same thing as above, just substitute the vectorAttack values for the controlVector values:

``````Vector3 towardsMouseFromPlayer = mousePos - transform.position;
vectorAttack = towardsMouseFromPlayer.normalized;
``````

This generally works but the problem is the distance the mouse is away from the player affects the numbers in vectorAttack. So clicking far away from them will cause you to go very fast and clicking on the player will make you basically stand still. If anyone has a good solution for this I’d really appreciate it as I’m having trouble finding a good answer. If the way I explained it didn’t make sense let me know and I’ll clarify, but for a visual example of what I’m going for I’m basically trying to recreate the same way your melee attacks work in Enter the Gungeon

Just double-checked it and I was using the correct vector2 for the attack movement. (Also the way you formatted that looks a lot cleaner so I switched it to that way, Thanks for that!)

But your reply actually pointed me in the right direction to figure out what was wrong! When I was getting the mouse position it was also grabbing its z position and that was throwing off the x and y when it normalized. I just made sure the towardsMouseFromPlayer.z is zero and now it works perfectly.

``````Vector3 towardsMouseFromPlayer = mousePos - transform.position;
towardsMouseFromPlayer.z = 0;
attackVector = towardsMouseFromPlayer.normalized;
``````

Are you sure that you use the variable “vectorAttack” and not the “towardsMousePlayer” variable? If the vector is normalized, it shouldn’t change it’s magnitude, it’s always has a length of 1 no matter how far the “mousePos” from the player is.

when moving

``````myRb.velocity = controlVector.normalized * moveSpeed;
``````

when attacking

``````Vector3 attackVector = mousePos - transform.position;
myRb.velocity = (Vector2) attackVector.normalized * moveSpeed;
``````