用按键控制物体移动的几种方法

 public float speed;
   
     int a = 0;
	
    void Update() {Force
        if (Input.GetKey(KeyCode.W))//利用ranslate实现物体的移动
        {
            this.gameObject.transform.Translate(Vector3.forward * speed, Space.World);
        }
        else if (Input.GetKey(KeyCode.S))//使用刚体的Velocity实现移动,Velocity本质上也是给物体一个力,但这个物体不具有惯性,停止施加力后,不会移动
        {
            this.gameObject.GetComponent<Rigidbody>().velocity = new Vector3(0, 0, 1);//velocity与已废弃的ConstantForce.force很相似
        }
        else if(Input.GetKey(KeyCode.A))//使用刚体的MovePosition实现移动,给定一个固定地点,让物体直接移动到固定地点,没有移动的过程
        {
            a++;
            this.gameObject.GetComponent<Rigidbody>().MovePosition(new Vector3(-a/5,0,0));        }
        else if(Input.GetKey(KeyCode.D))//利用刚体的AddForcc方法,给物体施加一个移动方向的力,物体具有惯性,停止施加力后,还会移动
        {
            this.gameObject.GetComponent<Rigidbody>().AddForce(new  Vector3(1,0,0)*10);
        }
    }

 还有一种不需要检测按键是否按下的方法

float x = Input.GetAxis("Horizontal");//检测输入A时返回-1,输入D时返回1
        float z = Input.GetAxis("Vertical");//检测输入w时返回-1,输入S时返回1
        this.gameObject.GetComponent<Rigidbody>().velocity = new Vector3(x, 0, z);//实现物体移动

 

 

posted on 2019-04-23 09:49  晴耕--雨读  阅读(182)  评论(0编辑  收藏  举报