这是我遇到的代码,实际上,当我按下空格键时,播放器将重复跳跃动画,甚至向右箭头也不再起作用。
如果您能帮助您,将不胜感激
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 ;
}
}
}
答案 0 :(得分:1)
别忘了将您的跳转设置为false
GetComponent<Animator>().SetBool("Jump", false);
当(不)按左箭头时,您还有一个else
。因此,您的向右箭头(未向左箭头)会将速度和速度设置为0。
答案 1 :(得分:0)
似乎您在此处将动画师Jump属性设置为'true'。
GetComponent<Animator>().SetBool("Jump", true);
您是否曾经将其设置为false?为了开始动画,您只希望它一次为true,然后应将其设置为false,这样动画就不会无休止地重复。