方法1
void Update()
{
if (Input.GetKey(KeyCode.W))
{
transform.Translate(Vector3.forward * moveSpeed * Time.deltaTime);
}
if (Input.GetKey(KeyCode.S))
{
transform.Translate(Vector3.back * moveSpeed * Time.deltaTime);
}
if (Input.GetKey(KeyCode.A))
{
transform.Translate(Vector3.left * moveSpeed * Time.deltaTime);
}
if (Input.GetKey(KeyCode.D))
{
transform.Translate(Vector3.right * moveSpeed * Time.deltaTime);
}
}
方法2
void Update()
{
float h= Input.GetAxis("Horizontal");
float v = Input.GetAxis("Vertical");
if (h!= 0 || v!= 0)
{
transform.Translate(new Vector3(h, 0, v) * Time.deltaTime * moveSpeed, Space.World);
}
}
方法3_通过刚体控制物体移动
void Update()
{
Vector3 moveForward = Vector3.zero;
if (Input.GetKey(KeyCode.W))
{
moveForward.z += 1;
}
if (Input.GetKey(KeyCode.S))
{
moveForward.z += -1;
}
if (Input.GetKey(KeyCode.A))
{
moveForward.x += -1;
}
if (Input.GetKey(KeyCode.D))
{
moveForward.x += 1;
}
GetComponent<Rigidbody>().MovePosition(Quaternion.LookRotation(transform.forward)
* moveForward * moveSpeed * Time.fixedDeltaTime + transform.position);
}
方法四_通过CharacterController组件控制移动
private CharacterController cha;
public float speed = 3;
void Start()
{
cha = GetComponent<CharacterController>();
}
void Update()
{
float h = Input.GetAxis("Horizontal");
float v = Input.GetAxis("Vertical");
cha.Move(new Vector3(h, 0, v) * speed * Time.deltaTime);
print(cha.isGrounded);
}
private void OnControllerColliderHit(ControllerColliderHit hit)
{
print(hit.collider);
}
5、示例
2D物体移动方法 以2Dtank图片为例
```csharp
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class OwnTank : MonoBehaviour
{
private float h;
private float v;
[Header("玩家坦克移动速度")]
public float ownTankMoveSpeed = 3;
private SpriteRenderer sr;
public Sprite[] spriteArray;
[Header("获取子弹预制体")]
public GameObject BulletPrefab;
private Vector3 bulletEulerAngles;
private float timeVal=0;
private void Awake()
{
sr = GetComponent<SpriteRenderer>();
}
void Update()
{
Attack();
}
private void FixedUpdate()
{
Move();
}
void Attack()
{
if (timeVal >= 0.4f)
{
if (Input.GetKeyDown(KeyCode.Space))
{
Instantiate(BulletPrefab, transform.position, Quaternion.Euler(transform.eulerAngles + bulletEulerAngles));
timeVal = 0;
}
}
else
{
timeVal += Time.deltaTime;
}
}
private void Move()
{
h = Input.GetAxisRaw("Horizontal");
transform.Translate(Vector3.right * h * ownTankMoveSpeed * Time.fixedDeltaTime, Space.World);
if (h < 0)
{
sr.sprite = spriteArray[2];
bulletEulerAngles = new Vector3(0, 0, 90);
}
else if (h > 0)
{
sr.sprite = spriteArray[3];
bulletEulerAngles = new Vector3(0, 0, -90);
}
if (h != 0)
{
return;
}
v = Input.GetAxisRaw("Vertical");
transform.Translate(Vector3.up * v * ownTankMoveSpeed * Time.fixedDeltaTime, Space.World);
if (v < 0)
{
sr.sprite = spriteArray[1];
bulletEulerAngles = new Vector3(0, 0, 180);
}
else if (v > 0)
{
sr.sprite = spriteArray[0];
bulletEulerAngles = new Vector3(0, 0, 0);
}
}
}