Unity Vector3.Dot(VectorA, VectorB)
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)与自身坐标轴(transform)
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轴方向
自身坐标轴的正方向代表三个默认的坐标。
- 通过判断飞机自身坐标轴Z轴与世界坐标轴Y轴来设置飞机阻力
Vector3.Dot(this.transform.forward, Vector3.up);
- 飞机在飞行过程中,transform.forward会一直改变,利用这一个特点,修改之前代码。
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;
}
}
因为作者精力有限,文章中难免出现一些错漏,敬请广大专家和网友批评、指正。
|