Transform.TransformDirection

本文详细介绍了Unity中TransformDirection函数的使用方法,该函数用于将局部空间中的方向转换到世界空间,并保持方向向量的长度不变。通过示例展示了如何使用此函数实现不同场景中的移动效果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


Transform.TransformDirection 变换方向

function TransformDirection (direction : Vector3) : Vector3

Description描述

Transforms direction from local space to world space.

从自身坐标到世界坐标变换方向。

This operation is not affected by scale or position of the transform. The returned vector has the same length as direction.

这个操作不会受到变换的缩放和位置的影响。返回的向量与direction有同样的长度。


实例说明:


m_cube是一个沿着X轴旋转了90度的方块。


方块沿着自身的z轴移动

m_cube.transform.Translate(Vector3.forward)



方块沿着世界的z轴移动

m_cube.transform.Translate(m_cube.transform.TransformDirection(Vector3.forward) );




/// <summary> /// Steering helper. /// </summary> private void SteerHelper() { // If vehicle is not grounded, return. if (!CarController.IsGrounded) return; // Return if kinematic rigid is enabled. if (CarController.Rigid.isKinematic) return; float correctedSteerHelper = steerHelperStrength * .35f; Vector3 localVelocity = transform.InverseTransformDirection(CarController.Rigid.velocity); float oldX = localVelocity.x; localVelocity.x *= (1f - (correctedSteerHelper * .25f)); float differenceX = Mathf.Abs(oldX) - Mathf.Abs(localVelocity.x); //if (differenceX >= .05f) { // if (localVelocity.x > 0) // localVelocity.x = Mathf.Clamp(localVelocity.x, oldX - (differenceX * correctedSteerHelper), Mathf.Infinity); // if (localVelocity.x < 0) // localVelocity.x = Mathf.Clamp(localVelocity.x, -Mathf.Infinity, oldX + (differenceX * correctedSteerHelper)); //} CarController.Rigid.velocity = transform.TransformDirection(localVelocity); CarController.Rigid.AddForce(-transform.right * localVelocity.x * correctedSteerHelper * .1f, ForceMode.VelocityChange); CarController.Rigid.AddForce(transform.right * correctedSteerHelper * (CarController.steerAngle / 40f) * Mathf.InverseLerp(10f, 60f, CarController.absoluteSpeed) * 1f, ForceMode.VelocityChange); int direction = 1; if (localVelocity.z < 0) direction = -1; // Adjusting angular velocity based on the steering angle and speed Vector3 angularVelocity = CarController.Rigid.angularVelocity; angularVelocity.y *= (1f - (correctedSteerHelper * .1f)); CarController.Rigid.angularVelocity = angularVelocity; CarController.Rigid.AddRelativeTorque(Vector3.up * angularVelocity.y * correctedSteerHelper * .125f * -direction, ForceMode.VelocityChange); CarController.Rigid.AddRelativeTorque(Vector3.up * correctedSteerHelper * (CarController.steerAngle / 40f) * Mathf.InverseLerp(0f, 80f, CarController.absoluteSpeed) * .75f * direction, ForceMode.VelocityChange); }
03-18
评论 9
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值