- Home /
AddForceAtPosition to Parent's rigidbody...C#
So I have a few gameobjects(I'll call them floatpoints) as children of a Boat which contains a rigidbody.
My intent is that when the float points (which are constantly raycasting upwards) get below a terrain which I have re-purposed into an "on trigger", shifting, perlin-noisey, wave-infused ocean they will apply upward force/torque to their parent's rigidbody at the position of the floatpoints themselves effectively simulating the realistic pitch/roll of a boat floating amongst waves.
Here is the code in it's entirety...
using UnityEngine;
using System.Collections;
public class RealisticFloat : MonoBehaviour {
public float hoverForce = 5.0F;
public float hoverDamp = 0.5F;
void Start() {
rigidbody.drag = 0.5F;
rigidbody.angularDrag = 0.5F;
}
void Update() {
int layerMask = 1 << 8;
RaycastHit hit;
Ray upRay = new Ray(transform.position, Vector3.up);
if (Physics.Raycast(upRay, out hit, 500f, layerMask)) {
float hoverError = hit.distance;
if (hoverError > 0) {
float upwardSpeed = rigidbody.velocity.y;
float lift = hoverError * hoverForce - upwardSpeed * hoverDamp;
transform.parent.rigidbody.AddForceAtPosition(lift * Vector3.up, transform.localPosition, ForceMode.Force);
}
}
}
}
...Now I know the majority of this code works as I've had objects float around when it is referring to itself and simply doing a...
rigidbody.AddForce(lift * Vector3.up);
...so I think the culprit is in this line...
transform.parent.rigidbody.AddForceAtPosition(lift * Vector3.up, transform.localPosition, ForceMode.Force);
...I think I am either not accessing the parent's rigidbody correctly or using "transform.localPosition" for my vector3 is not working as intended.
The code compiles fine but when I start my game my boat just falls through the "Ocean" without so much as a wobble (the lack of wobble tells me it isn't a matter of applying insufficient force as the terrain is shifting constantly on the update).
The scripts are within the floatpoints themselves fyi.
I am at a bit of a loss and have been scanning documentation and similar questions for days. If anyone could shed some light on what I am doing wrong I would be extremely grateful.
also sorry for being so wordy but details = clarity...
Okay I feel dumb...I got it working (kinda...) about a $$anonymous$$ute after submitting this question.
seems that I was defining the float "UpwardSpeed" I should have been referring to the parent's y velocity ins$$anonymous$$d of the floatpoint's y velocity.
Also on a humorous note the boat is spinning like crazy.
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
How can I access a collider's parent's rigidbody? 1 Answer
Making a haybale forkable 0 Answers
AddForce to position on Rigidbody 2 Answers