Transform.TransformDirection

本文详细解释了Unity引擎中TransformDirection函数的使用方法,并通过具体示例对比了使用TransformDirection和直接Translate的区别,帮助读者更好地理解如何在Unity中实现精确的对象移动。

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

transform.forward以自身坐标系为基准,向前


TransformDirection函数接受一个世界坐标下的向前Vector3.forward参数,转换成自身坐标系的向前

实例说明:


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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值