player movement with animations
This commit is contained in:
45
Assets/scripts/player-movement.cs
Normal file
45
Assets/scripts/player-movement.cs
Normal file
@ -0,0 +1,45 @@
|
||||
using Unity.VisualScripting;
|
||||
using UnityEngine;
|
||||
|
||||
public class player_movement : MonoBehaviour
|
||||
{
|
||||
public float speed = 10;
|
||||
// Start is called once before the first execution of Update after the MonoBehaviour is created
|
||||
[SerializeField] private Rigidbody2D body;
|
||||
private Animator anim;
|
||||
private bool grounded = true;
|
||||
|
||||
private void Awake(){
|
||||
//on load load the variables
|
||||
body = GetComponent<Rigidbody2D>();
|
||||
anim = GetComponent<Animator>();
|
||||
}
|
||||
private void Update(){
|
||||
float horizontal = Input.GetAxis("Horizontal");
|
||||
body.linearVelocity = new Vector2(horizontal * speed, body.linearVelocity.y);
|
||||
if (horizontal > 0.01)
|
||||
{
|
||||
GetComponent<SpriteRenderer>().flipX = false;
|
||||
}else if(horizontal < -0.01){
|
||||
GetComponent<SpriteRenderer>().flipX = true;
|
||||
}
|
||||
|
||||
if(Input.GetKey(KeyCode.Space) && grounded){
|
||||
|
||||
jump();
|
||||
}
|
||||
//run animation if horizontal not 0
|
||||
anim.SetBool("run", horizontal != 0);
|
||||
anim.SetBool("jump", !grounded);
|
||||
|
||||
}
|
||||
public void jump(){
|
||||
body.linearVelocity = new Vector2(body.linearVelocity.x, speed);
|
||||
grounded = false;
|
||||
}
|
||||
private void OnCollisionEnter2D(Collision2D collision){
|
||||
if(collision.gameObject.tag == "floor"){
|
||||
grounded = true;
|
||||
}
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user