Unity3D学习笔记2-应用脚本控制物体运动

来源:互联网 发布:免费越狱软件 编辑:程序博客网 时间:2024/06/06 18:01

在Assert/Script下创建新的C# Script,命名后会自动生成类,自动继承于MonoBehaviour类。增加简单的代码实现物体移动:
TestPlayer.cs

using System.Collections;using System.Collections.Generic;using UnityEngine;public class TestPlayer : MonoBehaviour {    //公有类成员变量,将会显示在Unity的Inspector界面中    public float walkSpeed = 2f;    // Use this for initialization    void Start () {    }    // Update is called once per frame    void Update () {        WalkForward();        return;    }    void FixedUpdate()    {        //和时间无关,所以移动需要把Time.deltaTime去掉,walkSpeed取值0.1即可        //transform.position = transform.position + walkSpeed * transform.forward;    }    void WalkForward()    {        transform.position = transform.position + walkSpeed * transform.forward * Time.deltaTime;    }}

然后将此TestPlayer.cs拖入相应物体(比如player)的Onspector界面中,你会看到可以控制改变类的公有变量walkSpeed值。运行即可看到物体player移动。


下面用一下LateUpdate实现一下 摄像机跟随的功能
创建TestSceneCamera.cs拖到Main Camera的Inspector中

using System.Collections;using System.Collections.Generic;using UnityEngine;public class TestSceneCamera : MonoBehaviour {    public GameObject player;    // Use this for initialization    void Start () {    }    // Update is called once per frame    void Update () {    }    void LateUpdate()    {        if(player != null)            this.transform.LookAt (player.transform.position);    }}

TestPlayer.cs的Start()函数中将自己指向 TestSceneCamera类中的player变量

……//省略代码见最上面TestPlayer.cspublic class TestPlayer : MonoBehaviour {    //公有类成员变量,将会显示在Unity的Inspector界面中    public float walkSpeed = 2f;    // Use this for initialization    void Start () {        //将自己指给TestSceneGame类中的player;        GameObject.Find("Main Camera").GetComponent<TestSceneCamera>().player = this.gameObject;    }……}

这样物体player移动的时候,摄像机一直望向(LookAt)player


总结笔记来自于视频教程:http://www.imooc.com/video/7334

阅读全文
0 0
原创粉丝点击