本帖最后由 u75379946 于 2016-3-8 18:36 编辑 在上一次的学习中我们介绍了unity3D脚本生命周期,今天我们来看看如何使用简单的脚本让我们的角色动起来。 首先我们看一个简单的: void Update () { float h = Input.GetAxis("Horizontal");//获取水平方向值 float v = Input.GetAxis("Vertical");//获取垂直方向值 transform.Translate(h,0,v);//通过Translate改变物体位置 }//通过坐标轴移动 将以上脚本拖给角色或物体,点击Play,按上下左右即可实现简单的移动了!(注意不要忘了加刚体) 下面我们再来看一个相似的: void FixedUpdate() { float h = Input.GetAxis("Horizontal"); float v = Input.GetAxis("Vertical"); Vector3 movement = new Vector3(h,0,v); GetComponent<Rigidbody>().velocity = movement; }//通过控制刚体速度移动物体 同样不要忘记加刚体组件,(上节讲过一般涉及物理状态的一般在FixedUpdate中写) 下面还有一个方法:为角色添加CharacterController(这个组件自动为我们添加了重力和碰撞还有坡度识别等) CharacterController characterController; public float speed = 4f; void Start () { characterController = GetComponent<CharacterController>(); } void Update () { float h = Input.GetAxis("Horizontal"); float v = Input.GetAxis("Vertical"); Vector3 movement = new Vector3(h, 0, v); characterController.SimpleMove(movement*speed); }//通过SimpleMove实现物体移动 下面我们看看如何实现相机跟随物体移动:在Scripts文件夹下建立一个FollowTarget.cs,将一下代码放入 public Transform target; public float smoothTime = 0.3F; private Vector3 velocity = Vector3.zero; void Update() { Vector3 targetPosition = target.TransformPoint(new Vector3(-5, 5, -5));//目标位置 transform.position = Vector3.SmoothDamp(transform.position, targetPosition, ref velocity, smoothTime);//相机平滑移动 }//相机跟随目标物体平滑移动 将脚本拖到相机上面,在Inspector下方我们可以看到: ![]() 我们可以看到Target还有Smooth Time变量,此时我们可以把需要跟随的角色目标拖到Target上,点击Play,随着目标的移动相机也在平滑的跟随,此时你还可以通过调整Smooth Time来控制平滑速率噢。 好了,心动不如行动,今天的Achor讲到的内容虽然简单,但是仍然需要你动手去实践,跟多细节值得你去自己体会噢。 最近公众微信中有很多朋友留言给Achor说:“由于刚入门,学到的知识很多很杂,容易忘怎么办!”今天送给大家的东西非常重要!!它可以帮助你记录和保存你所学到的知识,方便你定期回顾和梳理知识,Achor也一直在用,正所谓独乐乐不如众乐乐,就分享给大家吧! ![]() 最后,微信公众平台:黑客画家 以及我的 个人博客 :anchorart9.com 定期为大家分享游戏开发经验和行业最新资讯,需要的朋友可以关注一下我们相互学习哦! 本帖隐藏的内容![]() |
|