写一段unity2D的C#实现通过按下w来切换人物的动作(跳跃和站立)
时间: 2023-12-03 08:43:54 浏览: 28
下面是一个简单的Unity2D C#脚本,可以实现通过按下"W"键来切换人物的动作(跳跃和站立):
```csharp
using UnityEngine;
public class PlayerController : MonoBehaviour
{
private Animator animator;
// Start is called before the first frame update
void Start()
{
animator = GetComponent<Animator>();
}
// Update is called once per frame
void Update()
{
if (Input.GetKeyDown(KeyCode.W))
{
if (animator.GetBool("isJumping"))
{
animator.SetBool("isJumping", false);
}
else
{
animator.SetBool("isJumping", true);
}
}
}
}
```
这个脚本需要挂载到人物对象上。在Start函数中,我们获取了Animator组件的引用。在Update函数中,我们检测是否按下了"W"键。如果按下了,我们通过GetBool和SetBool方法来切换人物的动作状态。如果当前状态是跳跃状态,我们把isJumping设置为false,切换到站立状态;否则,我们把isJumping设置为true,切换到跳跃状态。