【Unity】6.4 Transform--移动、旋转和缩放游戏对象

分类:Unity、C#、VS2015

创建日期:2016-04-20

一、简介

Unity引擎提供了丰富的组件和类库,为游戏开发提供了非常大的便利,熟练掌握和使用这些API,对于游戏开发的效率提高很重要。

这一节我们主要学习Transform的基本用法。本节例子的运行效果如下:

image

二、Transform组件

场景中的每一个物体都有一个Transform。

Transform组件决定了游戏对象的位置、方向和缩放比例,如果希望在游戏中更新玩家位置、设置相机观察角度,都免不了要和Transform组件打交道。

每一个Transform可以有一个父级,允许你分层次应用位置、旋转和缩放。可以在Hierarchy面板查看层次关系。他们也支持计数器(enumerator),因此你可以使用循环遍历子物体。例如:

using UnityEngine;
using System.Collections;
public class example : MonoBehaviour
{
    public void Awake()
    {
        foreach (Transform child in transform)
        {
             child.position += Vector3.up * 10.0F;
        }
    }
}

1、成员变量

image

2、方法

image

例如(C#脚本):

void Update()
{
    //相对于自身坐标系统沿z轴向前移动物体(1单位/秒)
    transform.Translate(0, 0, Time.deltaTime);
    //在世界坐标系中向上移动物体(1单位/秒)
    transform.Translate(0, Time.deltaTime, 0, Space.World);
    //相对于摄像机向右移动物体(1单位/秒)
    transform.Translate(Vector3.right * Time.deltaTime, Camera.main.transform);
    //相对于自身坐标系统向右移动物体(1单位/秒)
    transform.Translate(Time.deltaTime, 0, 0, Camera.main.transform);
}

其中,relativeTo的选项有:

Space.Self--默认。相对于变换的自身轴移动。

Space.World--(当在场景视图选择物体时,x、y和z轴显示)相对于世界坐标系统移动。

三、示例

1、运行Unity,打开ch06Demos工程。

2、在Assets下添加名为6.4的子文件夹,然后在该文件夹下创建一个名为Scene6_4.unity的场景:

image

3、双击打开该场景。

4、向场景中添加一个圆柱体(Cylinder),并将其Y轴缩放改为5:

image

5、再向场景中添加一个lifangt(Cube),然后将X、Y、Z缩放系数全改为2:

image

6、调整摄像机位置,让圆柱体和立方体呈现出合适的大小:

image

7、在6.4文件夹中创建一个文件名为Demo4_1.cs的C#脚本:

image

8、双击Demo4_1,它就会自动启动VS2015,在VS2015中将Demo4_1.cs改为下面的代码并保存:

using UnityEngine;
using System.Collections;

public class Demo4_1 : MonoBehaviour
{
    public GameObject cube;
    public GameObject cylinder;
    void OnGUI()
    {
        if (GUILayout.Button("向左移动Cube"))
        {
            cube.transform.Translate(new Vector3(-0.5f, 0f, 0f));
        }
        if (GUILayout.Button("向右移动Cube"))
        {
            cube.transform.position = cube.transform.position + new Vector3(0.5f, 0f, 0f);
        }
        if (GUILayout.Button("放大Cube"))
        {
            cube.transform.localScale *= 1.2f;
        }
        if (GUILayout.Button("缩小Cube"))
        {
            cube.transform.localScale *= 0.8f;
        }
        if (GUILayout.Button("旋转Cube"))
        {
            cube.transform.Rotate(new Vector3(0, 10, 0));
        }
        if (GUILayout.Button("围绕圆柱旋转Cube"))
        {
            cube.transform.RotateAround(cylinder.transform.position, Vector3.up, 10);
        }
    }
}

9、切换到Unity,向场景中添加一个空的GameObject,然后将脚本拖放到检视器视图中,再将Cube和Cylinder分别拖放到脚本对应的属性下(赋初值):

image

10、按【播放】按钮,即可看到下面的预览效果:

image

多次单击不同的按钮或者同一个按钮,分别观察变化。

posted @ 2016-04-20 19:39  rainmj  阅读(9800)  评论(0编辑  收藏  举报