# Melee attack in the direction of the mouse

First of all, thanks for read this and sorry for my bad english.

I’m new in game development and im trying to make my first game, a 2D platformer.

My problem begins in the attack, im trying to make a melee attack(the attack is not done yet) in the direction of the mouse but when i try to normalize the vector in the direction of the mouse my vector displace and does not fit the direction of my mouse.

In summary, the yellow line doesnt go in the direction of the blue line.

Moreover if u know a easy way(or tutorial) to do a melee attack with mouse direction i would apreciate it.

My code:

if (Input.GetMouseButtonDown(0))
{
positionMouse = Camera.main.ScreenToWorldPoint(Input.mousePosition);

Vector2 hitBox = new Vector2(1, 1);

vectorAttack = positionMouse.normalized;

Vector2 puntoA = (Vector2)transform.position + vectorAttack - hitBox * 0.5f;
Vector2 puntoB = puntoA + hitBox;
}
Debug.DrawLine(transform.position, (Vector2)transform.position + vectorAttack, Color.yellow);
Debug.DrawLine(transform.position, positionMouse, Color.blue);

ScreenToWorldPoint returns a World Position. Any world position you can think of as a line connecting the world origin (0,0,0) to the position. When you normalize that (shorten the line to 1 unit), you get the direction from the world origin towards the mouse.

However you want the direction from the player object towards the mouse.

So you need to get the vector between the two positions, and normalize that:

``````positionMouse = Camera.main.ScreenToWorldPoint(Input.mousePosition);

// make the Z position equal to the player for a fully 2D comparison
positionMouse.z = transform.position.z;

Vector3 towardsMouseFromPlayer = positionMouse - transform.position;

vectorAttack = towardsMouseFromPlayer.normalized;
``````

Thank you so much!!!

If someone sees this thread u must do a cast as this:

Vector3 towardsMouseFromPlayer = positionMouse - (Vector2)transform.position;

Where do I put this code in the combat or movement script of do i make a new one?

You probably want to make a new thread and describe your problem in detail.