目录
在3D世界里,任何一个游戏对象在创建的时候都会附带transform(变换)组件,并且无法删除。
任何一个模型的三维坐标都保存在Vector3容器中,该容器记录模型在x轴、y轴、z轴方向的坐标。
平移游戏对象
transform.Translate()方法,唯一参数为平移的方向
示例:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class E4_08 : MonoBehaviour {
GameObject obj;
void Start () {
obj = GameObject.Find("Cube");
}
void OnGUI () {
if(GUILayout.Button("向前移动",GUILayout.Height(50)))
{
obj.transform.Translate(Vector3.forward * Time.deltaTime);
}
if (GUILayout.Button("向后移动", GUILayout.Height(50)))
{
obj.transform.Translate(Vector3.back * Time.deltaTime);
}
if (GUILayout.Button("向左移动", GUILayout.Height(50)))
{
obj.transform.Translate(Vector3.left * Time.deltaTime);
}
if (GUILayout.Button("向右移动", GUILayout.Height(50)))
{
obj.transform.Translate(Vector3.right * Time.deltaTime);
}
GUILayout.Label("立方体的位置:"+obj.transform.position);
}
}
旋转游戏对象
旋转方式分为自身旋转和围绕某点旋转
- transform.Rotate():该方法用于自身旋转,参数为旋转速度与方向
- transform.RotateAround():该方法用于围绕某一点旋转
- Vector3.right:x轴方向
- Vector3.up:y轴方向
- Vector3.forward:z轴方向
示例:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class E4_08rotate : MonoBehaviour {
GameObject objCube;
GameObject objCylinder;
int speed = 100; //旋转速度
void Start () {
objCube = GameObject.Find("Cube");
objCylinder = GameObject.Find("Cylinder");
}
void OnGUI()
{
if(GUILayout.Button("立方体沿x轴旋转",GUILayout.Height(50)))
{
objCube.transform.Rotate(Vector3.right * Time.deltaTime * speed);
}
if (GUILayout.Button("立方体沿y轴旋转", GUILayout.Height(50)))
{
objCube.transform.Rotate(Vector3.up * Time.deltaTime * speed);
}
if (GUILayout.Button("立方体沿z轴旋转", GUILayout.Height(50)))
{
objCube.transform.Rotate(Vector3.forward * Time.deltaTime * speed);
}
if (GUILayout.Button("立方体围绕圆柱体旋转", GUILayout.Height(50)))
{
objCube.transform.RotateAround(objCylinder.transform.position,Vector3.up ,Time.deltaTime * speed);
}
GUILayout.Label("立方体旋转角度:"+objCube.transform.rotation);
}
}
缩放游戏对象
缩放分为沿X、Y、Z轴缩放
示例:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class E4_08scale : MonoBehaviour {
GameObject obj;
float x = 1.0f;
float y = 1.0f;
float z = 1.0f;
void Start () {
obj = GameObject.Find("Cube");
}
void OnGUI()
{
GUILayout.Label("x轴缩放");
x = GUILayout.HorizontalSlider(x,1.0f,2.0f,GUILayout.Width(150));
GUILayout.Label("y轴缩放");
y = GUILayout.HorizontalSlider(y, 1.0f, 2.0f, GUILayout.Width(150));
GUILayout.Label("x轴缩放");
z = GUILayout.HorizontalSlider(z, 1.0f, 2.0f, GUILayout.Width(150));
obj.transform.localScale = new Vector3(x,y,z);
}
}