如何解决精灵没有在统一 2D C# 中移动
我正在学习制作游戏的教程,但当我写下他们写的内容时,它不会移动。
脚本附加到精灵,但当我点击 W、A、S 或 D 时,它不会不要动。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Movment : MonoBehavIoUr
{
// Start is called before the first frame update
public float speed = 5f;
void Start()
{
}
// Update is called once per frame
void Update()
{
float h = Input.GetAxis("Horizontal");
float v = Input.GetAxis("Vertical");
Vector2 pos = transform.position;
pos.x += h * speed * Time.deltaTime;
pos.y += v * speed * Time.deltaTime;
}
}
解决方法
由于 Vector2
是值类型(结构体),Vector2 pos = transform.position
将复制转换位置,并且原始位置不会受到您对 pos
所做的任何更改的影响。要更新位置,请在将 transform.position = pos
设置为新位置后使用 pos
:
void Update()
{
float h = Input.GetAxis("Horizontal");
float v = Input.GetAxis("Vertical");
Vector2 pos = transform.position;
pos.x += h * speed * Time.deltaTime;
pos.y += v * speed * Time.deltaTime;
transform.position = pos;
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。