制作好站立和移动的动画后
控制器设计
站立
移动
角色移动代码如下:
using System.Collections;
using System.Collections.Generic;
using Unity.VisualScripting;
using UnityEngine;public class p1_c : MonoBehaviour
{// 获取动画组件private Animator ani;// 获取刚体组件 2Dprivate Rigidbody2D rBody;// 移动方向Vector2 dir = new Vector2(0, 0);// 站立方向Vector2 h_v = new Vector2(0, 0);// 10 右 -10 左 // 01 上 0-1 下 void Start(){// 加载两个组件ani = GetComponent<Animator>();rBody = GetComponent<Rigidbody2D>();}// Update is called once per framevoid Update(){//float h = Input.GetAxis("Horizontal");//float v = Input.GetAxis("Vertical");// 10 右 -10 左 // 01 上 0-1 下 // 左if (Input.GetKeyDown(KeyCode.A) || (Input.GetKey(KeyCode.A))){dir = dir + new Vector2(-1, 0);h_v = new Vector2(-1, 0);}// 右if (Input.GetKeyDown(KeyCode.D) || (Input.GetKey(KeyCode.D))){dir = dir + new Vector2(1, 0);h_v = new Vector2(1, 0);}// 上if (Input.GetKeyDown(KeyCode.W) || (Input.GetKey(KeyCode.W))){dir = dir + new Vector2(0, 1);h_v = new Vector2(0, 1);}// 下if (Input.GetKeyDown(KeyCode.S) || (Input.GetKey(KeyCode.S))){dir = dir + new Vector2(0, -1);h_v = new Vector2(0, -1);}if ((dir[0] != 0) || (dir[1] != 0)){if (dir[0] > 1){dir[0] = 1;}if (dir[0] < -1){dir[0] = -1;}if (dir[1] > 1){dir[1] = 1;}if (dir[1] < -1){dir[1] = -1;}}if ((h_v[0] != 0) || (h_v[1] != 0)){if (h_v[0] > 1){h_v[0] = 1;}if (h_v[0] < -1){h_v[0] = -1;}if (h_v[1] > 1){h_v[1] = 1;}if (h_v[1] < -1){h_v[1] = -1;}}// 右 10 左 -1 0// 上 11 下 0 -1ani.SetFloat("H", h_v[0]);ani.SetFloat("V", h_v[1]);// 刚体 方向速度rBody.velocity = dir * 1f;// 获取ani.SetFloat("速度", dir.magnitude);// 松开if (Input.GetKeyUp(KeyCode.A) ||Input.GetKeyUp(KeyCode.W) ||Input.GetKeyUp(KeyCode.S) ||Input.GetKeyUp(KeyCode.D)){//Debug.Log("松开AWSD键");dir = new Vector2(0, 0);}}
}