Unity3D之如何让对象沿着自身坐标系移动 | 您所在的位置:网站首页 › scratch怎么让人物上下左右走 › Unity3D之如何让对象沿着自身坐标系移动 |
在写游戏中,你肯定想让物体沿着自身坐标系移动,如何做呢? 通过直接改变对象坐标实现: 法一: 自身z轴方向移动: transform.position += transform.forward * Input.GetAxis("Vertical") * Time.deltaTime; 自身x轴方向移动: transform.position += transform.right * Input.GetAxis("Vertical") * Time.deltaTime; 自身y轴方向移动: transform.position += transform.up * Input.GetAxis("Vertical") * Time.deltaTime;法二: 自身z轴方向移动: transform.Translate(Vector3.forward * Time.deltaTime * Input.GetAxis("Vertical"), Space.Self); 自身x轴方向移动: transform.Translate(Vector3.right * Time.deltaTime * Input.GetAxis("Vertical"), Space.Self); 自身y轴方向移动: transform.Translate(Vector3.up * Time.deltaTime * Input.GetAxis("Vertical"), Space.Self); 用速度来控制对象的移动:要使对象有速度可以,肯定要先添加组件 下面是代码: using System.Collections; using System.Collections.Generic; using UnityEngine; public class PlayerMove : MonoBehaviour { public float rotationSpeed; public float MoveSpeed; void Update () { if (Input.GetButton("Horizontal") || Input.GetButton("Vertical")) { transform.GetComponent().velocity = transform.forward * Input.GetAxis("Vertical") * MoveSpeed + transform.right * Input.GetAxis("Horizontal") * MoveSpeed; } transform.Rotate(new Vector3(0, Input.GetAxis("Mouse X"), 0) * rotationSpeed, Space.Self); } } 用力来控制对象的移动:下面是代码: using System.Collections; using System.Collections.Generic; using UnityEngine; public class PlayerMove : MonoBehaviour { public float rotationSpeed; public float MoveSpeed; void Update () { if (Input.GetButton("Horizontal") || Input.GetButton("Vertical")) { transform.GetComponent().AddForce(transform.forward * Input.GetAxis("Vertical") * MoveSpeed + transform.right * Input.GetAxis("Horizontal") * MoveSpeed); } transform.Rotate(new Vector3(0, Input.GetAxis("Mouse X"), 0) * rotationSpeed, Space.Self); } }上面两个都是沿着水平方向移动的,当然你也可以通过实际情况进行更改。
|
CopyRight 2018-2019 实验室设备网 版权所有 |