Vector3.Dot(VectorA, VectorB) 等于 VectorA * VectorB。
而对于两个向量的乘积计算:
VectorA * VectorB = Ax * Bx + Ay * By + Az * Bz
例如:
VectorA(1,2,3) * VectorB(4,5,6) = 1*4+2*5+3*6=32
一般应用于判断飞行器是否收到阻力,这里利用飞机进行举例。
Vector3.up #Y轴正方向(0,1,0)
Vector3.down #Y轴反方向(0,-1,0)
Vector3.forward #Z轴正方向(0,0,1)
Vector3.back #Z轴反方向(0,0,-1)
Vector3.right #X轴正方向(1,0,0)
Vector3.left #X轴反方向(-1,0,0)
this.transform.up #自身Y轴方向
this.transform.forward #自身Z轴方向
this.transform.right #自身X轴方向
Vector3.Dot(this.transform.forward, Vector3.up);
Vector3.Dot(this.transform.forward, Vector3.up)
#飞机径直向前值为0
#飞机机头向上由0到1变化
#飞机机头向下由0到-1变化
float hinderForce = 1 - Vector3.Dot(this.transform.forward, Vector3.up);
#飞机径直向前hinderForce为1
#飞机机头向上hinderForce为[0,1]的数
#飞机机头向下hinderForce为[-1,0]的数
rb.velocity = this.transform.forward * Speed * hinderForce
#当飞机机头向下既可加速冲刺,而机头向上向前的速度将减缓
整个飞机的控制脚本(Script):
注:需要在飞机添加刚体组件
[SerializeField]
private float maxFlySpeed = 150;//飞行速度
[SerializeField]
private float minAllowFlySpeed = 40;//最小允许飞行速度
[SerializeField]
private float addSpeed = 20;//提速速度
[SerializeField]
private float currentSpeed;//当前速度
private float perAddSpeed;//单位提升速度
[SerializeField]
private float gravitySpeed = 30;//重力下降速度
private Rigidbody rb;
private void Start()
{
rb = this.GetComponent<Rigidbody>();
perAddSpeed = addSpeed / maxFlySpeed;
}
void Update()
{
float hinderForce = 1 - Vector3.Dot(this.transform.forward, Vector3.up);
if (Input.GetKey(KeyCode.J))
{
AddSpeed();
if (hinderForce < 0.2f)
{
rb.useGravity = true;
rb.velocity = Vector3.down * gravitySpeed;//加速自由落体
}
else
{
rb.useGravity = false;
rb.velocity = this.transform.forward * currentSpeed * hinderForce;
}
}
else
{
rb.useGravity = true;
subtractSpeed();
rb.velocity = this.transform.forward * currentSpeed * hinderForce + Vector3.down * gravitySpeed;//平滑飞行
}
if (currentSpeed > minAllowFlySpeed)
{
if (Input.GetKey(KeyCode.A))
{
this.transform.Rotate(new Vector3(0, 0, Time.deltaTime * 100));
}
else if (Input.GetKey(KeyCode.D))
{
this.transform.Rotate(new Vector3(0, 0, Time.deltaTime * -100));
}
if (Input.GetKey(KeyCode.W))
{
this.transform.Rotate(new Vector3(Time.deltaTime * -30, 0, 0));
}
else if (Input.GetKey(KeyCode.S))
{
this.transform.Rotate(new Vector3(Time.deltaTime * 30, 0, 0));
}
}
}
//速度提升
private void AddSpeed()
{
if (currentSpeed >= maxFlySpeed)
{
currentSpeed = maxFlySpeed;
}
else
{
currentSpeed += perAddSpeed;
}
}
//减小速度
private void subtractSpeed()
{
if (currentSpeed <= 0)
{
currentSpeed = 0;
}
else
{
currentSpeed -= perAddSpeed * 1.3f;
}
}
因为作者精力有限,文章中难免出现一些错漏,敬请广大专家和网友批评、指正。