由于最新版的unity已经不支持javascript语言啦,本人又是个C#小白,所以记录一下自己写的脚本。

first 创建一个模型,放在平面上,调整下角度,就像这样:

1.使用脚本控制模型的移动 --《Unity 3D 游戏开发》笔记-LMLPHP

然后写一个脚本来控制模型移动:

public class NewBehaviourScript : MonoBehaviour {

    //首先定义两个变量,public是公有变量,在程序中可以直接访问,私有变量只能在脚本中访问
//此处定义模型移动速度以及模型旋转速度
public int TranslateSpeed = ;
public int RotateSpeed = ; //OnGUI方法绘制页面组件
void OnGUI()
{
//设置GUI背景颜色
GUI.backgroundColor = Color.red; //GUI.Button设置一个按钮,返回true时表示按钮被按下
//Rect一个由X和Y位置、宽度和高度定义的2D矩形
if (GUI.Button(new Rect(, , , ), "向左旋转"))
{
//向左旋转模型
transform.Rotate(Vector3.up * Time.deltaTime * (-RotateSpeed));
//transform为当前绑定模型的变换对象
//Vector3.up = Vector3(0, 1, 0)
//Vector3表示三维向量x,y,z,此处向左旋转,括号中负号应该表示沿y轴逆时针
//Time.deltaTime只读属性,表示完成最后一帧的时间,单位为秒
}
if (GUI.Button(new Rect(, , , ), "向前移动"))
{
//向前移动模型
transform.Translate(Vector3.forward * Time.deltaTime * TranslateSpeed);
//Vector3(0, 0, 1)
}
if (GUI.Button(new Rect(, , , ), "向右旋转"))
{
//向右旋转模型
transform.Rotate(Vector3.up * Time.deltaTime * RotateSpeed);
}
if (GUI.Button(new Rect(, , , ), "向后移动"))
{
//向后移动模型
transform.Translate(Vector3.forward * Time.deltaTime * (-TranslateSpeed));
}
if (GUI.Button(new Rect(1, , , ), "向左移动"))
{
//向左移动模型
transform.Translate(Vector3.right * Time.deltaTime * (-TranslateSpeed));
//Vector3(1, 0, 0)
}
if (GUI.Button(new Rect(170, , , ), "向右移动"))
{
//向右移动模型
transform.Translate(Vector3.right * Time.deltaTime * TranslateSpeed);
} //GUI.Label设置一个文本框
//显示模型位置信息
GUI.Label(new Rect(, , , ), "模型的位置" + transform.position);
//显示模型旋转信息
GUI.Label(new Rect(, , , ), "模型的旋转" + transform.rotation); }
}

脚本写完了以后会发现我们定义的变量出现在模型的属性栏里了

1.使用脚本控制模型的移动 --《Unity 3D 游戏开发》笔记-LMLPHP

然后点击play,就出现了这样的界面:

1.使用脚本控制模型的移动 --《Unity 3D 游戏开发》笔记-LMLPHP

我把脚本绑定在立方体上啦,点击左上角的按钮它就会到处跑哦,由于我给它添加了刚体属性,还会撞到其它模型,real有趣

emmm第一个实例 完成~

撒花~✿✿ヽ(°▽°)ノ✿

04-13 17:16