运动方式1
修改 position / localPosition ,可以让物体运动
例如,
Vector3 pos = this.transform.localPosition;
pos.z += distance;
this.transform.localPosition = pos;
此时,小车向+Z 方向运动
具体代码如下
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SimpleLogic : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
float speed = 1;
float distance = speed * Time.deltaTime;
Vector3 pos = this.transform.localPosition;
pos.z += distance; // 0.005f;
this.transform.localPosition = pos;
}
}
运动方式2
一般使用 transform.Translate () ,实现相对运动
transform.Translate( dx, dy, dz , ..)
其中,dx , dy, dz 是坐标增量
例如,
transform.Translate(0, 0, distance); // Z 方向增加 distance
代码如下
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SimpleLogic : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
float speed = 1;
float distance = speed * Time.deltaTime;
this.transform.Translate(distance, 0, distance);
}
}
相对运动
物体的相对运动,只需在transform.Translate(0, 0, distance);参数里添加一个参数this.transform.Translate(distance, 0, distance,Space.Self); //自己的坐标
this.transform.Translate(distance, 0, distance,Space.World);//世界坐标
物体运动方向
运动的方向,使物体朝着目标方向运动
1 获取目标物体
GameObject flag = GameObject.Find("目标物体名称");
2 转向目标
this.transform.LookAt(flag.transform);
3 向‘前’运动 ,forward ,+Z 方向
this.transform.Translate(0, 0, dz , Space.Self);
其中, GameObject.Find ( name_or_path) ,根据名字/路径来查找物体 transform.LookAt ( target ) ,使物体的 Z轴 指向物体 Space.self ,沿物体自身坐标系的轴向运动
代码如下
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SimpleLogic : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
GameObject flag = GameObject.Find("目标物体名称");
this.transform.LookAt(flag.transform);
}
// Update is called once per frame
void Update()
{
float speed = 1;
float distance = speed * Time.deltaTime;
this.transform.Translate(0, 0, distance, Space.Self);
}
}