Over the course of development i have changed Player and Enemy movement and knockback various times but none have really stuck with me. All of the ways i have tried have been clunky in one way or another.
Here is my current enemy movement:
// If target is to the left
if(target.transform.position.x < transform.position.x){
if(body.velocity.x >= -0.3 && body.velocity.x <= 0.3){
// speed boost
body.AddForce(-transform.right * speedBoost, ForceMode2D.Impulse);
}
body.AddForce(-transform.right * speed);
movingLeft = true;
}
else{
if(body.velocity.x >= -0.3 && body.velocity.x <= 0.3){
// speed boost
body.AddForce(transform.right * speedBoost, ForceMode2D.Impulse);
}
body.AddForce(transform.right * speed);
movingLeft = false;
}
}
Vector3 clampVel = body.velocity;
clampVel.x = Mathf.Clamp(clampVel.x, -maxXSpeed, maxXSpeed);
body.velocity = clampVel;
and knockback:
public void knockback(Vector3 position, float force){
body.velocity = Vector2.zero;
body.angularVelocity = 0f;
var dir = transform.position - position;
body.AddForce(dir * force, ForceMode2D.Impulse);
}
This actually works pretty well, however since i am clamping x velocity, knock backs on the x plane are all the same force past a certain point, whilst knockbacks on the y plane are much higher.
Player movement:
float moveX = Input.GetAxis ("Horizontal");
if(canMove == true){
body.velocity = new Vector2((moveX * speed) + body.velocity.x, body.velocity.y);
}
Vector3 clampVel = body.velocity;
clampVel.x = Mathf.Clamp(clampVel.x, -maxXValue, maxXValue);
body.velocity = clampVel;
I want Terraria style knockback and smooth movement. Could anybody give me any hints for smooth movement and knockback for both enemies and the Player?
Thanks.
EDIT: It also has to work with other movement, for example abilities that slam the Player into the ground, blink, etc.