美文网首页
Unity-变换组件移动物体,键盘控制移动方向

Unity-变换组件移动物体,键盘控制移动方向

作者: a04a42f99657 | 来源:发表于2017-02-22 23:49 被阅读351次
  • 1-变换组件移动物体
    
游戏物体与组件.png

这幅图现在理解还不深刻,先放在这,日后再来补全。

  • 1.1相关方法
    首先要将脚本挂到这个cube上,然后在这个脚本里面编辑。

  • gameObject.getcomponent<Transform>();获取相关组件的引用。
    假定这个对象为cubeTransform.
    这个方法要写在start()里面,从游戏开始就要获取到这个组件。
    这个方法要返回一个Transform类型的对象。

  • 1.2
    然后调用这个对象的Translate方法,
    Transform.Translate(Vector3, Space):
    两个参数
    (Vector3)表示三维向量,
    向量可以表示一个方向和一个位置。
    Space是一个枚举。
    Space.self和Space.World分别表示自身坐标系和世界坐标系。

  • 2键盘控制移动方向。

       void Update () {
     if(Input.GetKey(KeyCode.W))
    {
       _cubeTransform.Translate(Vector3.forward * 1f*Time.deltaTime,Space.Self);
    }
     if(Input.GetKey(KeyCode.S))
    {
       _cubeTransform.Translate(Vector3.back * 1f * Time.deltaTime, Space.Self);
    }
      if(Input.GetKey(KeyCode.A))
    {
       _cubeTransform.Translate(Vector3.left * 1f * Time.deltaTime, Space.Self);
    }
    if (Input.GetKey(KeyCode.D))
    {
       _cubeTransform.Translate(Vector3.right * 1f * Time.deltaTime, Space.Self);
    }

相关文章

网友评论

      本文标题:Unity-变换组件移动物体,键盘控制移动方向

      本文链接:https://www.haomeiwen.com/subject/efkvwttx.html