Raycast Suspension acts weird when moving away from Origin

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By Alef

Hi there,

So Ive tried to fix this for a few days myself now but couldnt find a solution so i decided to ask here. Might be a easy fix actually and Im just stupid lol.

I am trying to create a Vehicle/Car that has a Raycast Suspension and I got that working as long as I am close to the Origin of the scene but as soon as I drop the “vehicle” anywhere further away from Origin it goes crazy. I am assuming it has something to do with the local and global position but at this point I think I tried every posibility of global and local combinations and it either gives the same result or it just flies away.

My Setup:
I have a Truck Scene which is just a RigidBody with a mesh and collision attached to it. On the Corners of the Mesh I have another scene attached which includes the “suspension”.
The Suspension consists of a Node3D which has a Raycast and a Note3D as a child.
The Note3D acts as a indicator where the ray intersects with the ground and so that I can calculate the speed of that given point.

The Suspension has a GDScript attached to it tp calculate the force needed to keep up the Vehicle.
springStrength has a constant value of 100.0, springDamper of 5.0 and suspensionRestDist of 1.0 while the raycast length is -2

func _physics_process(delta):
if(suspension.is_colliding()):
	WheelAttchment.global_position = suspension.get_collision_point()
	
	springDir = suspension.get_collision_normal()
	tireWorldVel = get_parent().linear_velocity + get_parent().angular_velocity.cross(WheelAttchment.global_position - get_parent().global_position)
	offset = suspensionRestDist - (suspension.get_collision_point() - suspension.global_transform.origin).length()
	vel = springDir.dot(tireWorldVel)
	force = (offset * springStrength) - (vel * springDamper)
	
	get_parent().apply_force(force * springDir, WheelAttchment.global_position)

I got my inforamtion on how this should work from this Video here.

Id be very happy if someone know how to fix that and could share that with me.
Thanks a lot :slight_smile:

:bust_in_silhouette: Reply From: TRAILtheGREAT

I think your problem is that last line:
get_parent().apply_force(force * springDir, WheelAttchment.global_position)

reading the docs for Rigidbody3D:
position is the offset from the body origin in global coordinates.”

so while you are correct to use WheelAttachment’s global position, the position of the force is relative to the origin of the rigidbody, not the world origin, so you should subtract the position of the car body:
get_parent().apply_force(force * springDir, WheelAttchment.global_position - get_parent().global_position)

Yes it worked. Thank you so much

Alef | 2023-04-28 05:11