Reputation: 1
This the code I am having issues with, in fact when I press the space button, the player will just repeat the animation of jump and even the right arrow doesn't work anymore.
Please if you could help you will be more than welcome
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Player : MonoBehaviour
{
Rigidbody2D rb2d;
public float Speed = 30f;
public float JumpForce = 30f;
bool Jump;
float speed;
private bool FacingRight;
// Start is called before the first frame update
void Start()
{
FacingRight = true;
rb2d = GetComponent<Rigidbody2D>();
rb2d.velocity = Vector2.zero;
}
// Update is called once per frame
void Update()
{
if (Input.GetKey(KeyCode.Space))
{
GetComponent<Animator>().SetBool("Jump", true);
}
if (Input.GetKey(KeyCode.RightArrow))
{
GetComponent<Animator>().SetFloat("speed", 1);
rb2d.velocity = Vector2.right * Speed * Time.deltaTime;
}
if (Input.GetKey(KeyCode.LeftArrow))
{
GetComponent<Animator>().SetFloat("speed", 1);
rb2d.velocity = Vector2.left * Speed * Time.deltaTime;
}
else
{
GetComponent<Animator>().SetFloat("speed", 0f);
rb2d.velocity = Vector2.zero;
}
}
private void FixedUpdate()
{
float horizontal = Input.GetAxis("Horizontal");
Flip(horizontal);
}
private void Flip (float horizontal)
{
if (horizontal > 0 && !FacingRight || horizontal < 0 && FacingRight)
{
FacingRight = !FacingRight;
Vector3 theScale = transform.localScale;
theScale.x *= -1;
transform.localScale = theScale;
}
}
void OnCollisionEnter2D(Collision2D col)
{
if (col.gameObject.name ==" Front_Buildings")
{
GetComponent<Animator>().SetBool("isGrounded", true);
rb2d.velocity = Vector2.zero ;
}
}
}
Upvotes: 0
Views: 84
Reputation: 3704
Don't forget to set your jump back to false
GetComponent<Animator>().SetBool("Jump", false);
Also you have an else
when the left arrow is (not) pressed. So your right arrow (which is not left) will set the speed and velocity to 0.
Upvotes: 1
Reputation: 414
It looks like you set the animator Jump attribute to 'true' here.
GetComponent<Animator>().SetBool("Jump", true);
Do you ever set this back to false? You only want it to be true once, in order to begin the animation, then it should be set back to false so that the animation does not just repeat endlessly.
Upvotes: 0