方法1:使用transform.Translate()函数
using UnityEngine;
public class MoveDemo : MonoBehaviour
{
private void Update()
{
GetInput();
}
//获取键盘输入的操作
public void GetInput()
{
if (Input.GetKey(KeyCode.W))
{
this.gameObject.transform.Translate(Vector3.forward * Time.deltaTime);
}
if (Input.GetKey(KeyCode.S))
{
this.gameObject.transform.Translate(Vector3.down * Time.deltaTime);
}
if (Input.GetKey(KeyCode.A))
{
this.gameObject.transform.Translate(Vector3.left * Time.deltaTime);
}
if (Input.GetKey(KeyCode.D))
{
this.gameObject.transform.Translate(Vector3.right * Time.deltaTime);
}
}
}
方法2:使用Rigidbody2D组件
using UnityEngine;
public class MoveDemo : MonoBehaviour
{
public float moveSpeed = 3.0f;
Rigidbody2D rb2d;
Vector2 inputPos;
private void Start()
{
rb2d = gameObject.GetComponent();
inputPos = new Vector2();
}
private void Update() { }
//获取物理操作
private void FixedUpdate()
{
MoveObject();
}
public void MoveObject()
{
//获取键盘操作的水平数值
inputPos.x = Input.GetAxisRaw("Horizontal");
//获取键盘操作的垂直数值
inputPos.y = Input.GetAxisRaw("Vertical");
//向量归一,使其移动速度一致。
inputPos.Normalize();
//移动速率
rb2d.velocity = inputPos * moveSpeed;
}
}
向右方向固定移动
方法1:transform.localPosition
using UnityEngine;
public class MoveDemo : MonoBehaviour
{
private void FixedUpdate()
{
MoveRigth();
}
//移动
public void MoveRigth()
{
Vector2 pos = gameObject.transform.localPosition;
//向右 * 每帧数时间
pos += Vector2.right * Time.deltaTime;
//移动
gameObject.transform.localPosition = pos;
}
}
方法2:使用Rigidbody2D组件
using UnityEngine;
public class MoveDemo : MonoBehaviour
{
//速度
public float moveSpeed = 3.0f;
Rigidbody2D rb2d;
private void Start()
{
//获取Rigidbody2D组件
rb2d = gameObject.GetComponent();
}
private void Update() { }
//获取物理操作
private void FixedUpdate()
{
MoveRigth();//
}
//向右移动
public void MoveRigth()
{
//速率
rb2d.velocity = Vector2.right * moveSpeed;
}
}



