Я пытаюсь создать свой собственный колесный коллайдер. У меня это работает довольно хорошо в будущем, но когда я поворачиваю колесо, это не реагирует очень реалистично. Иногда это становится так, как должно (вроде), но когда я также применяю газ. Он вращается в другую сторону и скользит в пончик. Я не совсем знаю, как решить эту проблему. Я знаю, что модель колесного коллайдера сейчас очень проста, но я хочу, чтобы вперед и рулевое управление было в основном первым, прежде чем продвигаться дальше с моей моделью колеса.[Header("Wheel Parameters")]
public float radius = 0.35f;
public float grip = 1f;
public float outputForce;
public bool showStats = false;
[Header("Steering & Alignment")]
public bool isSteerable = false;
public float maxSteeringAngle = 30f;
[Header("References")]
public Transform wheelVisual;
public bool showDebug = true;
private float steeringAngle;
[HideInInspector] public Vector3 wheelForward { get; private set; }
public override void Simulate(float dt)
{
outputForce = torque / radius;
// Geometry
steeringAngle = isSteerable ? car.steerInput * maxSteeringAngle : 0f;
Quaternion steerRot = Quaternion.Euler(0f, steeringAngle, 0f);
// Calculate effective orientation
Quaternion combinedRotation = steerRot;
wheelForward = combinedRotation * transform.forward;
Vector3 wheelRight = combinedRotation * transform.right;
// Calculate wheel linear speed
float wheelLinearSpeed = angularVelocity * radius;
if (showStats) Debug.Log($"Wheel Linear Speed: {wheelLinearSpeed}");
float forwardVelocity = Vector3.Dot(car.carRb.linearVelocity, transform.forward);
if (showStats) Debug.Log($"Forward Velocity: {forwardVelocity}");
// Calculate simple slip ratio
float slipRatio = (wheelLinearSpeed - forwardVelocity) / Mathf.Max(Mathf.Abs(forwardVelocity), 1f);
slipRatio = Mathf.Clamp(slipRatio, -1f, 1f);
if (showStats) Debug.Log($"Slip Ratio: {slipRatio}");
// Linear traction model
outputForce = slipRatio * grip * 100f; // Scale for force realism
if (Mathf.Abs(outputForce) < 0.001f) outputForce = 0f;
// Resistance torque from ground force
float resistingTorque = outputForce * radius;
if (showStats) Debug.Log($"Resisting Torque: {resistingTorque}");
// Apply net torque
float netTorque = torque - resistingTorque;
if (showStats) Debug.Log($"Net Torque: {netTorque}");
// Integrate angular acceleration
UpdateAngularVelocityFromTorque(netTorque, dt);
// Apply forces
//Vector3 force = wheelForward * outputForce;
//car.carRb.AddForceAtPosition(force, transform.position);
// Visual
UpdateVisual();
// Debug
}
private void UpdateVisual()
{
if (wheelVisual != null)
{
//wheelVisual.position = for suspension work
wheelVisual.Rotate(Vector3.right, angularVelocity * Mathf.Rad2Deg * Time.fixedDeltaTime);
Vector3 angles = wheelVisual.localEulerAngles;
wheelVisual.localEulerAngles = new Vector3(0f, steeringAngle, 0f);
}
}
< / Code> public carcontroller Car; < / P>
public List wheels = new();
void FixedUpdate()
{
float dt = Time.fixedDeltaTime;
//Vector3 totalForce = Vector3.zero;
foreach (var wheel in wheels)
{
wheel.Simulate(dt);
Vector3 force = wheel.wheelForward * wheel.outputForce;
car.carRb.AddForceAtPosition(force, wheel.transform.position);
// Apply force from each wheel to the car Rigidbody
//totalForce += wheel.wheelForward * wheel.outputForce;
//car.carRb.AddForceAtPosition(force, wheel.transform.position);
//Debug.Log("Applying Force");
}
//car.carRb.AddForce(totalForce);
}
Подробнее здесь: https://stackoverflow.com/questions/796 ... ks-forward
Пользовательский колесный коллайдер не поворачивается, как следовало бы, но работает вперед ⇐ C#
Место общения программистов C#
1752069260
Anonymous
Я пытаюсь создать свой собственный колесный коллайдер. У меня это работает довольно хорошо в будущем, но когда я поворачиваю колесо, это не реагирует очень реалистично. Иногда это становится так, как должно (вроде), но когда я также применяю газ. Он вращается в другую сторону и скользит в пончик. Я не совсем знаю, как решить эту проблему. Я знаю, что модель колесного коллайдера сейчас очень проста, но я хочу, чтобы вперед и рулевое управление было в основном первым, прежде чем продвигаться дальше с моей моделью колеса.[Header("Wheel Parameters")]
public float radius = 0.35f;
public float grip = 1f;
public float outputForce;
public bool showStats = false;
[Header("Steering & Alignment")]
public bool isSteerable = false;
public float maxSteeringAngle = 30f;
[Header("References")]
public Transform wheelVisual;
public bool showDebug = true;
private float steeringAngle;
[HideInInspector] public Vector3 wheelForward { get; private set; }
public override void Simulate(float dt)
{
outputForce = torque / radius;
// Geometry
steeringAngle = isSteerable ? car.steerInput * maxSteeringAngle : 0f;
Quaternion steerRot = Quaternion.Euler(0f, steeringAngle, 0f);
// Calculate effective orientation
Quaternion combinedRotation = steerRot;
wheelForward = combinedRotation * transform.forward;
Vector3 wheelRight = combinedRotation * transform.right;
// Calculate wheel linear speed
float wheelLinearSpeed = angularVelocity * radius;
if (showStats) Debug.Log($"Wheel Linear Speed: {wheelLinearSpeed}");
float forwardVelocity = Vector3.Dot(car.carRb.linearVelocity, transform.forward);
if (showStats) Debug.Log($"Forward Velocity: {forwardVelocity}");
// Calculate simple slip ratio
float slipRatio = (wheelLinearSpeed - forwardVelocity) / Mathf.Max(Mathf.Abs(forwardVelocity), 1f);
slipRatio = Mathf.Clamp(slipRatio, -1f, 1f);
if (showStats) Debug.Log($"Slip Ratio: {slipRatio}");
// Linear traction model
outputForce = slipRatio * grip * 100f; // Scale for force realism
if (Mathf.Abs(outputForce) < 0.001f) outputForce = 0f;
// Resistance torque from ground force
float resistingTorque = outputForce * radius;
if (showStats) Debug.Log($"Resisting Torque: {resistingTorque}");
// Apply net torque
float netTorque = torque - resistingTorque;
if (showStats) Debug.Log($"Net Torque: {netTorque}");
// Integrate angular acceleration
UpdateAngularVelocityFromTorque(netTorque, dt);
// Apply forces
//Vector3 force = wheelForward * outputForce;
//car.carRb.AddForceAtPosition(force, transform.position);
// Visual
UpdateVisual();
// Debug
}
private void UpdateVisual()
{
if (wheelVisual != null)
{
//wheelVisual.position = for suspension work
wheelVisual.Rotate(Vector3.right, angularVelocity * Mathf.Rad2Deg * Time.fixedDeltaTime);
Vector3 angles = wheelVisual.localEulerAngles;
wheelVisual.localEulerAngles = new Vector3(0f, steeringAngle, 0f);
}
}
< / Code> public carcontroller Car; < / P>
public List wheels = new();
void FixedUpdate()
{
float dt = Time.fixedDeltaTime;
//Vector3 totalForce = Vector3.zero;
foreach (var wheel in wheels)
{
wheel.Simulate(dt);
Vector3 force = wheel.wheelForward * wheel.outputForce;
car.carRb.AddForceAtPosition(force, wheel.transform.position);
// Apply force from each wheel to the car Rigidbody
//totalForce += wheel.wheelForward * wheel.outputForce;
//car.carRb.AddForceAtPosition(force, wheel.transform.position);
//Debug.Log("Applying Force");
}
//car.carRb.AddForce(totalForce);
}
Подробнее здесь: [url]https://stackoverflow.com/questions/79695646/custom-wheel-collider-not-turning-as-it-should-but-works-forward[/url]
Ответить
1 сообщение
• Страница 1 из 1
Перейти
- Кемерово-IT
- ↳ Javascript
- ↳ C#
- ↳ JAVA
- ↳ Elasticsearch aggregation
- ↳ Python
- ↳ Php
- ↳ Android
- ↳ Html
- ↳ Jquery
- ↳ C++
- ↳ IOS
- ↳ CSS
- ↳ Excel
- ↳ Linux
- ↳ Apache
- ↳ MySql
- Детский мир
- Для души
- ↳ Музыкальные инструменты даром
- ↳ Печатная продукция даром
- Внешняя красота и здоровье
- ↳ Одежда и обувь для взрослых даром
- ↳ Товары для здоровья
- ↳ Физкультура и спорт
- Техника - даром!
- ↳ Автомобилистам
- ↳ Компьютерная техника
- ↳ Плиты: газовые и электрические
- ↳ Холодильники
- ↳ Стиральные машины
- ↳ Телевизоры
- ↳ Телефоны, смартфоны, плашеты
- ↳ Швейные машинки
- ↳ Прочая электроника и техника
- ↳ Фототехника
- Ремонт и интерьер
- ↳ Стройматериалы, инструмент
- ↳ Мебель и предметы интерьера даром
- ↳ Cантехника
- Другие темы
- ↳ Разное даром
- ↳ Давай меняться!
- ↳ Отдам\возьму за копеечку
- ↳ Работа и подработка в Кемерове
- ↳ Давай с тобой поговорим...
Мобильная версия