文章来自:吾爱分享-程序员社区
第一种移动方式:
首先在方法外声明刚体:private Rigidbody body;
为了明显,可定义一个速度:public float speed;
void Start(){
speed = 10f;
body = GetCompoente();
}
void Update(){
//第一种移动方式:直接修改Transform属性
//如果是球体,自身不会旋转
if(Input.GetKey(KeyCode.W))
{
this.gameObject.transform.Translate(Vector3.forwardTime.deltaTime);
}
if(Input.GetKey(KeyCode.S))
{
this.gameObject.transfrom.Translate(Vector3.downTime.deltaTime);
}
if(Input.GetKey(KeyCode.A))
{
this.gameObject.Tramsfrom.Translate(Vector.leftTimg.deltaTime);
}
if(Input.GetKey(KeyCode.D))
{
this.gameObject.Transform.Translate(Vector.rightTime.deltaTime);
}
第二种移动方式:给刚体施加力,如果是球体,会发生旋转
if(Input.GetKey(KeyCode.W))
{
body.AddForce(Vector3.forwwardspeed,ForceMode.Force);
}
if(Input.GetKey(KeyCode.S))
{
body.AddForce(Vector3.backspeed,ForceMode.Force);
}
if(Input.GetKey(KeyCode.A))
{
body.AddForce(Vector3.leftspeed,ForceMode.Force);
}
if(Inpute.GetKey(KeyCode.D))
{
body.AddForce(Vector3.rightspeed,ForceMode.Force);
}
第三种移动方式:直接获取游戏的水平以及垂直值
可以直接在Update方法中声明
float h = Input.GetAxis(“Horizontal”);
float v = Input.GetAxis(“Vertical”);
this.Transform.Translate(new Vector3(hTime.deltaTimespeed,0f,vTime.deltaTimespeed));
}