Unity有一些自带的快捷键
在 Unity 中,点击“Edit” -> “Project Settings” -> “Input Manager”
例如:我们下面会用到的,“Horizontal” 与键盘上的左右方向键(← 和 →)以及 “A” 和 “D” 键关联,还有Jump关联键盘上的空格键。
编写人物左右移动的脚本代码:
使用 Input.GetAxisRaw 方法获取玩家在水平方向上的输入,返回值为 -1(向左)、0(静止)或 1(向右),将其存储在变量 dirX 中。
rb.velocity = new Vector2(dirX * 7f, rb.velocity.y);:通过修改 Rigidbody2D 组件的速度属性来控制游戏对象在水平方向上的移动。Vector2 是二维向量,dirX * 7f 计算出水平方向的速度,垂直方向的速度保持不变。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Playermovement : MonoBehaviour
{
private Rigidbody2D rb;
// Start is called before the first frame update 第一次运行
void Start()
{
rb=GetComponent<Rigidbody2D>();
}
// Update is called once per frame 反复运行
void Update()
{
//水平方向速度
float dirX