normalize speed and move at the direction of mouse;

Hello

I am working on 2D top down shooter game.

I used the transform.translate in my movement script, and it worked great, so the movement would go in the direction where the player was facing.

So if i pressed the “up” key and the player was looking down, then he would move down. Basiclly where ever the mouse pointe was as the player would look at that direction.

But i could not figure out how to use the normalize so i had constant speed also in the diagonal movement. So i change my movememt script, that fixed the normalize move but now if i press “up” key, even though i am looking down, the plater will move up.

Here below the new code:

float moveX = Input.GetAxisRaw("Horizontal");
       float moveY = Input.GetAxisRaw("Vertical");
        moveDirection = new Vector2(moveX, moveY).normalized;




            rb.velocity = new Vector2(moveDirection.x * moveSpeed, moveDirection.y * moveSpeed);


            var speed = Mathf.Abs(moveDirection.x) + Mathf.Abs(moveDirection.y);

And here the old code:

  //horizontal = Input.GetAxisRaw("Horizontal");
         //vertical = Input.GetAxisRaw("Vertical");

      
        

   
            rb.velocity = new Vector2(horizontal * moveSpeed, vertical * moveSpeed);


           transform.Translate(Vector2.left * Time.deltaTime * moveSpeed * horizontal);
          transform.Translate(Vector2.down * Time.deltaTime * moveSpeed * vertical);

            var speed = Mathf.Abs(moveDirection.x) + Mathf.Abs(moveDirection.y);

erm… this code is pretty bonkered.

in the old code you moved your object twice and you explicitly moved it by Vector2.down in the transform.Translate
in the new code you don’t have this bit so its only moved by the rigidbody.velocity
and we don’t know where movespeed is coming from… or where movedirection came from in the old script.

if you want to move an object into the direction its looking, just use transform.translate(transform.forward * time.deltatime * movespeed) this will always go same speed and always go wherever it faces (if your object has the right forward vector) or if you wanna use rigidbody, you can say rg.velocity = transform.forward * movespeed