c# - 试图用箭头键移动 1 个对象,用 wasd 移动另一个对象
问题描述
我正在开发一个 2D 游戏,我想用箭头键移动一个左块,用 A 和 D 移动一个右块,但我只能用 WASD 或箭头键移动,我对 C# 和统一。
我尝试制作 2 个“水平”,方法是在项目设置中制作一个 A 和 D,另一个用左箭头和右箭头键制作,但这似乎不起作用,非常感谢:*)
这是给玩家 1
public float speed;
private Rigidbody2D rb;
private Vector2 moveVelocity;
private void Start()
{
rb = GetComponent<Rigidbody2D>();
}
void Update()
{
Vector2 moveInput = new Vector2(Input.GetAxisRaw("Horizontal1"), 0f);
moveVelocity = moveInput.normalized * speed;
}
void FixedUpdate()
{
rb.MovePosition(rb.position + moveVelocity * Time.fixedDeltaTime);
}
播放器 2 是相同的代码,只是使用 ("Horizontal2")
解决方案
您可以Input.GetKey(KeyCode)
用来读取玩家的输入。此外,在检查器中为每个玩家分配 KeyCode。
这是一个可能有帮助的示例代码:
public KeyCode leftKey = KeyCode.A; // Change to KeyCode.LeftArrow in inspector
public KeyCode rightKey = KeyCode.D;
public float speed = 1.0f;
private Vector2 _moveVelocity;
private RigidBody2D _rigidBody;
private void Start()
{
_rigidBody = GetComponent<Rigidbody2D>();
}
private void Update()
{
Vector2 moveInput = Vector2.zero;
if(Input.GetKey(leftKey))
{
moveInput = Vector2.left;
}
if(Input.GetKey(rightKey))
{
moveInput = Vector2.right;
}
_moveVelocity = moveInput * speed * Time.deltaTime;
_rigidBody.velocity = _moveVelocity;
}
推荐阅读
- ruby-on-rails-4 - Rails 自定义错误页面工作和不工作
- oracle - 函数中调用过程
- javascript - 如何在 slickgrid 单元格内呈现 angularjs 指令
- cakephp - 在 cakephp 3.x 中使用存储过程
- awk - 如何在同一字段中查找/打印两个相反符号的连续浮点数?
- python - 如何通过 API 从 Telegram 组获取消息 - Python
- memory - 我正在尝试通过很多步骤使用 5 维数组。我收到一个错误:''std::bad_alloc''
- javascript - 需要将元素替换为数组中右侧元素的最大值
- java - 设置后清除工具栏菜单(启动活动时)
- visual-studio - 自动缩进破坏文件的缩进