首先把代码实现给大家放出来:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerControl : MonoBehaviour
{
private Animator ani;
private Rigidbody2D rBody;
// Start is called before the first frame update
void Start()
{
ani=GetComponent<Animator>();
rBody=GetComponent<Rigidbody2D>();
}
// Update is called once per frame
void Update()
{
float horizontal = Input.GetAxisRaw("Horizontal");
float vertical = Input.GetAxisRaw("Vertical");
if(horizontal!=0)
{
ani.SetFloat("Horizontal", horizontal);
ani.SetFloat("Vertical", 0);
}
if (vertical != 0)
{
ani.SetFloat("Horizontal",0);
ani.SetFloat("Vertical", vertical);
}
Vector2 dir = new Vector2(horizontal, vertical);
ani.SetFloat("Speed",dir.magnitude);
rBody.velocity = dir * 0.5f;
}
}
下面我们来做详细解释:
1、引入命名空间
using System.Collections;
using System.Collections.Generic;
using UnityEngine
这些命名空间用于引入所需的类和功能。
System.Collections 和 System.Collections.Generic 包含一些常用的集合类和泛型集合类。
UnityEngine 是Unity引擎的核心命名空间,包含所有Unity的功能和组件。
2、脚本类和组件
public class PlayerControl : MonoBehaviour
定义了一个名为 PlayerControl 的公共类,它继承自 MonoBehaviour 类。这意味着我们可以使用 MonoBehaviour 类提供的所有功能,并且可以附加这个脚本到任何Unity对象上。
3、属性
private Animator ani;
private Rigidbody2D rBody;
定义了两个私有变量:
ani: 存储对Animator组件的引用。Animator组件用于控制角色的动画。
rBody: 存储对Rigidbody2D组件的引用。Rigidbody2D组件用于模拟2D物理运动。
4. Start() 方法
void Start()
{
ani=GetComponent<Animator>();
rBody=GetComponent<Rigidbody2D>();
}
在 Start() 方法中,我们使用 GetComponent() 函数获取 Animator 和 Rigidbody2D 组件的引用,并将其存储在相应的变量中。
5. Update() 方法
void Update()
{
float horizontal = Input.GetAxisRaw("Horizontal");
float vertical = Input.GetAxisRaw("Vertical");
if(horizontal!=0)
{
ani.SetFloat("Horizontal", horizontal);
ani.SetFloat("Vertical", 0);
}
if (vertical != 0)
{
ani.SetFloat("Horizontal",0);
ani.SetFloat("Vertical", vertical);
}
Vector2 dir = new Vector2(horizontal, vertical);
ani.SetFloat("Speed",dir.magnitude);
rBody.velocity = dir * 0.5f;
}
在 Update() 方法中,我们每帧都会获取用户的输入(水平轴和垂直轴)。然后,我们根据输入更新 Animator 组件的值,并使用这些值来设置角色的速度和方向。
Input.GetAxisRaw() 函数获取用户输入的原始轴值。
检查水平轴和垂直轴的值,如果不为0,则设置相应的动画参数。
创建一个 Vector2 对象 dir,表示角色的移动方向。
使用 ani.SetFloat() 方法设置角色的速度和方向。
使用 rBody.velocity 设置角色的实际速度。