I have an object that I want to keep on the ground through Linecasts rather than gravity (currently just have one Linecast for simplicity). The Linecast goes from the center of the object, to an empty child which is positioned just below the parent’s base (so it always hits the ground). Whenever the Linecast hits, the object’s Y position is changed to the Linecast’s point of contact with the ground (+1 unit for accommodate for the object Y scale).
If the object is stationary everything is fine, same if I move it sideways (on X and Z axis). But whenever there’s upward movement, whether through a slope or me just dragging the object using the Inspector window, the Linecast starts vibrating vertically. This will continue to happen until I detach the object from the ground and place it back on a flat surface. When detaching it, either via inspector upwards, or moving it off the edge of another object, there’s a sudden small launch upwards.
This also happens when I spam the jump key, and when the object jumps, it goes extra high (even when jumping from a flat surface).
Note, this only happens if the Linecast is vibrating.
Here’s the code for the Linecast (and the code I believe is causing the issue).
RaycastHit hitInfo;
if (Physics.Linecast(transform.position, bottomObject.position, out hitInfo) && hitInfo.collider.tag != "Char") {
Debug.DrawLine(transform.position, bottomObject.position, Color.green);
transform.position = new Vector3(transform.position.x, hitInfo.point.y + 1f, transform.position.z);
}
else Debug.DrawLine(transform.position, bottomObject.position, Color.red);
After days of testing and changing code back and forth, I narrowed it down to being the “transform.position”.
I made two debug prints, one showing the position of the Linecast impact point, and the other showing the position of the object’s empty child. Though it didn’t really matter what the second debug printed, and here’s why. Whatever part of the object (either it or its children) I printed the position of, the Y part would always jump up by 0.1, and then back down by 0.1 (meaning it was the whole object being moved, not just a child). This happens 2-3 times a second whenever the Linecast is shaking.
I’m running the Linecast code in Update, and anything that changes forces, velocity, etc, in FixedUpdate. And since I know now what the issue is, I won’t post the full script (unless someone requests more code).
What can I do to stop this? I read somewhere on an unrelated problem’s thread that shaking could be the transform.position and rigidbody (I have a rigidbody to add my own gravity at specific points) fighting over object placement, since maybe the object is being teleported into geometry, but this is happening even when I add more than 1 to the Vector3 line’s Y change, and the object is constantly floating.
