Hello,
I have a spaceship and an asteroid. The asteroid is moving to X axis (negative value) with constant speed, let’s say 2.5, and ship is moving along X and Y axis with constant speed of 5. If the ship is moving on the same direction with the asteroid then the “speed” of the asteroid is constant, but if the ship is moving in the opposite direction, then the “speed” is increasing.
I want that the asteroid to move with constant “speed” relative to the ship.
I know that it’s something related to physics, but I don’t know how to code.
Here’s a sample gif:
Asteroid Update Script:
void Update()
{
// Rotate asteroid
float z = transform.rotation.eulerAngles.z;
z -= speedRotation * Time.deltaTime;
transform.rotation = Quaternion.Euler(0, 0, z);
// Move Asteroid
Vector3 pos = transform.position;
pos += Vector3.left * speed * Time.deltaTime;
transform.position = pos;
}
Ship Update Script:
void Update ()
{
// Rotate Ship
float z = transform.rotation.eulerAngles.z;
z -= Input.GetAxis("Horizontal") * speedRotation * Time.deltaTime;
rot = Quaternion.Euler(0, 0, z);
transform.rotation = rot;
// Move Ship
Vector3 pos = transform.position;
Vector3 velocity = new Vector3(0, Input.GetAxis("Vertical") * speed * Time.deltaTime, 0);
pos += rot * velocity;
transform.position = pos;
directionX = transform.position.x - prevDirectionX;
}
Thank you.