Unity3D功能开发入门系列(三)
一、运动脚本
准备工作:
- 布置测试场景,添加小火车
- 添加脚本 SimpleLogic,控制小火车移动
(一)物体的运动
一般使用 transform.Translate( ),实现相对运动
transform.Translate( dx, dy, dz, …) ,其中 dx, dy, dz 是坐标增量
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MoveLogic : 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;
this.transform.Translate(distance, 0, distance);
}
}
(二)相对运动
transform.Translate( dx, dy, dz, space),其中第 4 个参数:
-
Space.World,相对于 世界坐标系
-
Space.Self,相对于 自身坐标系(本地坐标系)<更常用>
在建模时,要求物体的 脸的朝向 与物体 +Z轴 一致
(三)运动的方向
使物体朝着目标方向移动(这里以小红旗为例),到达目标后停下来
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using static Unity.IO.LowLevel.Unsafe.AsyncReadManagerMetrics;
public class MoveLogic : 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()
{
GameObject flag = GameObject.Find("红旗");
Vector3 p1 = this.transform.position;
Vector3 p2 = flag.transform.position;
Vector3 p = p2 - p1;
float distance = p.magnitude; // magnitude 取向量的模
if(distance > 0.3f)
{
float speed = 2;
float move = speed * Time.deltaTime;
this.transform.Translate(0, 0, move, Space.Self);
}
}
}
- 其中:
GameObject.Find( name_or_path),根据 名字 / 路径 查找物体
transform.LookAt( target),使物体的 Z轴 指向 target 物体(若目标在空中,火车就原地起飞了)
Space.self,沿物体自身坐标系的轴向运动- 如果想让视角随着物体运动
二、旋转脚本
(一)物体的旋转
给物体调转一个旋转的角度
- Quaternion 四元组(x, y, z, w)
transform.rotation = … 不便操作,官方也不建议使用 - 欧拉角 Euler Angle
transform.eulerAngles = new Vector3( 0, 45, 0);
transform.localEulerAngles = new Vector( 0, 45, 0);
注:new Vector( 0, 45, 0)、new Vector( 0, 405, 0)、new Vector( 0, -315, 0) 效果相同
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class RotateLogic : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
Application.targetFrameRate = 60;
}
// Update is called once per frame
void Update()
{
float rotateSpeed = 60; // 每秒转 60°
Vector3 angles = this.transform.localEulerAngles;
angles.y += rotateSpeed * Time.deltaTime; //0.5f;
this.transform.localEulerAngles = angles;
}
}
(二)相对旋转
Rotate( ),旋转一个相对角度
transform.Rotate( dx, dy, dz, space)
using System.Collections;
using System.Collections.Generic;
using UnityEngine;<