一、添加角色
// 我使用的是中文版编辑器
1、在层级页面:
// 我的角色比较椭圆,所以使用的是胶囊形状。
右键点击——2D对象——Sprites——胶囊。
2、在检查器页面:
将角色图画拖到Sprite Renderer的精灵上。
并为角色添加组件——Rigidbody 2D、Capsule Collider 2D(胶囊)。
然后给角色对象挂载Player.cs脚本。
2D游戏中如果不想人物往下掉可以将Rigidbody 2D的重力设置为0。
二、角色方向移动
1、Player.cs代码实现
using UnityEngine;
public class Player : MonoBehaviour
{
public float speed = 5f; // 用于控制角色移动的速度
void Update()
{
// 按下键盘WASD来控制角色移动
float horizontalInput = Input.GetAxis("Horizontal");
float verticalInput = Input.GetAxis("Vertical");
// 根据输入方向调整角色的位置
Vector3 movement = new Vector3(horizontalInput, verticalInput, 0) * speed * Time.deltaTime;
transform.position += movement;
}
}