需求:实现物体前后左右定向平移,无需转向;
代码实现:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ScriptOfTransformTranslateAndRotateMove : MonoBehaviour
{
public float moveSpeed = 4f;
public float rotateSpeed = 100f;
void Update()
{
if (Input.GetKey("w"))
{
this.transform.Translate(new Vector3(0, 0, moveSpeed * Time.deltaTime));
}
if (Input.GetKey("s"))
{
this.transform.Translate(new Vector3(0, 0, -moveSpeed * Time.deltaTime));
}
if (Input.GetKey("a"))
{
this.transform.Rotate(new Vector3(0, -rotateSpeed * Time.deltaTime, 0), Space.World);
}
if (Input.GetKey("d"))
{
this.transform.Rotate(new Vector3(0, rotateSpeed * Time.deltaTime, 0), Space.World);
}
}
}
代码段说明:
此代码只支持物体的硬平移,不包含转向(自动或者手动)和朝向功能。
|