If you have the direction vector, then you can do “direction * speed” to get the force needed to move in that direction. I did that in the example class, using “input” as my direction vector.
If your direction vector isn’t normalized (vector length of 1), or you’re not sure, use the “.normalized” property on the vector when using it as a direction, this will make sure the vector length will equal 1, and won’t mess with your speed value when you multiply. (see below for syntax)
If you want to find a random direction, you can use “UnityEngine.Random.insideUnitCircle”, which will give you a random normalized Vector2 (length of 1) to use as a direction.
Here’s the same example class which gets a random direction to move in at the start:
using UnityEngine;
[RequireComponent(typeof(Rigidbody2D))]
public class PhysicsMovement : MonoBehaviour {
public float acceleration;
public float deceleration;
private Rigidbody2D physics;
private Vector2 direction;
private void Start() {
physics = GetComponent<Rigidbody2D>();
physics.gravityScale = 0;
physics.drag = deceleration;
direction = UnityEngine.Random.insideUnitCircle;
}
private void FixedUpdate() {
Vector2 directionalForce = direction * acceleration;
physics.AddForce(directionalForce * Time.deltaTime, ForceMode2D.Impulse);
}
}
If you want the object to move towards another object, you can get that movement direction by doing:
(otherObjectPosition - thisObjectPosition).normalized
and using that vector in your “direction * speed” calculation.
So with that you should be able to see how you can either move randomly, or move towards a checkpoint or target of sorts.
Also just a tip, you can use these shorthands to get normalized cardinal directions:
Vector2.right, Vector2.left, Vector2.up, Vector2.down.
These are equivalent to Vector2(1,0), Vector2(-1,0), Vector2(0,1), Vector2(0,-1), respectively.