Easiest way to move a rigidbody2d diagonally

i can move an object up or down using the below
but i cant work out diagonal movement.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Asteroid1 : MonoBehaviour
{
    public float speed = 1f;
   
    public Rigidbody2D rb;

    // Update is called once per frame
    void Update()
    {
        rb.velocity = transform.right * speed;
       
    }
}
var direction = (transform.right + transform.up).normalized;
rb.velocity = direction * speed;

BTW you can probably just do this once in Start(). No need to run it every frame. The physics engine will take care of continuous motion since you set the velocity.

1 Like

You’re setting velocity in terms of local space of the object (transform.right).

You can add others if you like:

rb.velocity = transform.right * SpeedRightward + transforrm.up * SpeedUpward;

If you want global speeds replace transform with Vector3

oh for goodness sake, never thought of doing that, had 2 separate lines trying to execute different directions. thanks PraetorBlue!!! again.

The “normalized” is important too, otherwise your diagonal movement will be faster than horiz/vert…about 1.4X as much, square root of 2.

3 Likes