Hi! I’m developing a 2D spaceship game for Android and I’m using one joystick prefab from mobile assets to either move the spaceship and rotate it at the same time. However, the game feels very unrealistic as the ship accelerates to its full speed almost instantly. I would like to make the ship accelerate smoother until its full speed, which I would be able to pre-set. And also upon changing the directions with joystick I would like to slowly decelerate the spacehip and start accelerating in the opposite direction. Here’s the code I have so far + joystick.cs script from mobile assets. Many thanks
public Joystick joystick; // Reference to joystick prefab
public float speed = 10; // Movement speed
private float h = 0, v = 0; // Horizontal and Vertical values
public float rotation_speed = 0.1; // Rotation speed of spaceship
void Update(){
h = joystick.position.x;
v = joystick.position.y;
if (Mathf.Abs(h) > 0) {
rigidbody2D.velocity = new Vector2(h * speed, rigidbody2D.velocity.y);
}
if (Mathf.Abs(v) > 0) {
rigidbody2D.velocity = new Vector2(rigidbody2D.velocity.x, v * speed);
}
if (Mathf.Abs(h) == 0 || Mathf.Abs(v) == 0){
gameObject.transform.rigidbody2D.drag = 1;
}
else{
var angle = Mathf.Atan2(h,v) * Mathf.Rad2Deg;
transform.rotation = Quaternion.Slerp(transform.rotation,Quaternion.Euler(0,0,-angle),rotation_speed);
}
}
EvilTak
2
Instead of directly changing the velocity, use Rigidbody2D.AddForce. That will give you the required result. Just add a force vector according to your input, and then limit the velocity. Somewhat like this:
h = joystick.position.x;
v = joystick.position.y;
rigidbody2d.AddForce(joystick.position * accel); //accel is a public variable which defines the acceleration force.
rigidbody2D.velocity = rigidbody2D.velocity.normalized * topSpeed;