Unity中C#代码学习用wasd和上下左右键控制物体前后左右上下移动和绕轴旋转
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class wasd上下 : MonoBehaviour
{
public GameObject chedao;
public GameObject dizuo;
public GameObject zhuanpan;
public GameObject center;
public GameObject shangti;
//定义物体
public float speed = 0.1f;
public float Angels=1;
//定义移动速度和旋转速度
// Start is called before the first frame update
// Update is called once per frame
void FixedUpdate()
//用fixedupdate中0.02秒更新一次(不过后面用的Time.deltaTime不知道受不受这个影响)
{
//前后移动的部分
if (Input.GetKey(KeyCode.W))
//如果键盘按下W键
{ chedao.transform.localPosition = new Vector3(chedao.transform.localPosition.x , chedao.transform.localPosition.y + Time.deltaTime * speed, chedao.transform.localPosition.z); }
//chedao物体的局部坐标改变,X不变,Y方向改变1秒钟乘以speed的值是移动的速度,Z不变
if (Input.GetKey(KeyCode.S))
{ chedao.transform.localPosition = new Vector3(chedao.transform.localPosition.x, chedao.transform.localPosition.y - Time.deltaTime * speed, chedao.transform.localPosition.z); }
//dizuo移动部分
if (Input.GetKey(KeyCode.A))
{ dizuo.transform.localPosition = new Vector3(dizuo.transform.localPosition.x- Time.deltaTime * speed,dizuo.transform.localPosition.y,dizuo.transform.localPosition.z); }
if (Input.GetKey(KeyCode.D))
//zhuanpan转动部分
{dizuo.transform.localPosition = new Vector3(dizuo.transform.localPosition.x + Time.deltaTime * speed, dizuo.transform.localPosition.y, dizuo.transform.localPosition.z); }
//——————————————上下左右箭头操作————————————————————————————————————————
if (Input.GetKey(KeyCode.LeftArrow))
//底盘顺时针旋转(左箭头)
{ zhuanpan.transform.RotateAround(center.transform.position, Vector3.up, Angels * Time.deltaTime); }
//选装用transform.RotateAround这个方法(旋转物体,用了tramsform.RotateArpindlz里面的参数,画图的位置对象,center.transform.position是旋转的中心也就是绕谁旋转,Vector3.up是指定了一个轴(是center对象的x轴,会绕x轴进行旋转),最后是移动速度和旋转数度)
if (Input.GetKey(KeyCode.RightArrow))
//底盘逆时针旋转(右箭头)
{ zhuanpan.transform.RotateAround(center.transform.position, Vector3.down, Angels * Time.deltaTime); }
if (Input.GetKey(KeyCode.UpArrow))
//上体上移(上箭头)
{ shangti.transform.localPosition = new Vector3(shangti.transform.localPosition.x, shangti.transform.localPosition.y , shangti.transform.localPosition.z - Time.deltaTime * speed); }
if (Input.GetKey(KeyCode.DownArrow))
//上体下移(下箭头)
{ shangti.transform.localPosition = new Vector3(shangti.transform.localPosition.x, shangti.transform.localPosition.y , shangti.transform.localPosition.z + Time.deltaTime * speed); }
}
}