Rigidbody2D rigid;
float h;
private void Awake()
{
rigid = GetComponent<Rigidbody2D>();
}
private void FixedUpdate()
{
h = Input.GetAxisRaw("Horizontal");
rigid.AddForce(Vector2.right * h, ForceMode2D.Impulse);
}
rigid.AddForce(Vector2.right * h, ForceMode2D.Impulse);
AddForce
is a method that can apply force to rigidbody 2D.
We are not using any specified Vector2
value, so we'll use Vector2.right
Reason why we're using Vector2.right
is because .right
is a positive number. If we did .left
the gameObject will move opposite as to where we want it to move since it's negative number.
To make it move, we will multiply h
value to Vector2.right
We will use ForceMode2D.Impulse
to move our player gameObject.
- When using
AddForce
method, there'sForceMode2D.Impulse
andForceMode2D.Force
.
ForceMode2D.Force
applies continuous force to the gameObject.ForceMode2D.Impulse
applies instant force to the gameObject.
- This is because we wrote the code in
FixedUpdate()
- We are applying instant force to the rigidbody 2D for every 50 frames, which is why it's accelerating.
To stop this from happening, we can set MaxSpeed value.
//if rigid's positive x velocity is bigger than the maxSpeed
//then rigid's positive x velocity is maxSpeed
//if rigid's negative x velocity is bigger than the maxSpeed * -1
//then rigid's negative x velocity is maxSpeed * -1
if(rigid.velocity.x > maxSpeed)
{
rigid.velocity = new Vector2(maxSpeed, rigid.velocity.y);
}
else if(rigid.velocity.x < maxSpeed * (-1))
{
rigid.velocity = new Vector2(maxSpeed * (-1), rigid.velocity.y);
}
Now we should be able to move our player gameObject.
new Vector2
value when the player stops pressing onto the keyboard.Pseudo Code:
//if the player stops pressing the keyboard, //then rigid will assign new x velocity value to decrease speed.
Apply to the code:
private void Update()
{
if (Input.GetButtonUp("Horizontal"))
{
rigid.velocity = new Vector2(rigid.velocity.normalized.x, rigid.velocity.y);
}
}
We will use Update()
since we want to consistently decrease the gameObject's velocity.
normalized
converts the Vector
to a unit vector, meaning it will have magnitude to 1 while maintaining the original direction.
Setting the tilesmap(platform) so the gameObject doens't collide with individual tilemap.