unity2d平台跳跃无反应_pipixia2002的博客-爱代码爱编程
学Unity的第一天,跟着B站M_Studio的一个教程做,想着记点笔记记录一下我遇到的问题和解决方案。
问题:
在做角色的前后移动时,是在void Fixed Update()中写的
void FixedUpdate()
{
Move();
}
void Move()
{
float horizontalmove = Input.GetAxisRaw("Horizontal");
rb.velocity = new Vector2(horizontalmove * speed * Time.fixedDeltaTime, rb.velocity.y);
if (horizontalmove != 0)
{
transform.localScale = new Vector3(horizontalmove, 1, 1);
}
}
于是我控制跳跃的代码也理所应当的写在了Move函数里,结果前后移动正常,跳跃反应不出来。
原因:
在查看文档后发现我的因为我的代码前后移动为了适应所有电脑,乘了Time.fixedDeltaTime,因此把Move函数放在了FixedUpdate()里,而读取Jump的GetButtonDown应在运用在upDate()中.
解决问题后的代码
public class playerController : MonoBehaviour
{
public Rigidbody2D rb;
public float speed;
public float jumpForce;
public bool isJump=false;
// Start is called before the first frame update
void Start()
{
}
private void Update()
{
if (Input.GetButtonDown("Jump"))
{
isJump = true;
}
}
// Update is called once per frame
void FixedUpdate()
{
Move();
Jump();
}
void Move()
{
float horizontalmove = Input.GetAxisRaw("Horizontal");
rb.velocity = new Vector2(horizontalmove * speed * Time.fixedDeltaTime, rb.velocity.y);
if (horizontalmove != 0)
{
transform.localScale = new Vector3(horizontalmove, 1, 1);
}
}
void Jump()
{
if(isJump)
{
rb.velocity = new Vector2(rb.velocity.x, jumpForce * Time.fixedDeltaTime);
isJump = false;
}
}
}
文章仅仅是我对自己学习的记录