Hey folks.
Here is some code that me and an AI came up with for
working around an issued caused by linear drag.
Specifically, increasing drag causes a player to ‘float’ if
they move too fast from higher to lower ground.
The script I proposed creates a ‘snap’ offset, for when
to trigger a vertical decline back to the ground + another ‘hover offset’
I know, right. You’re welcome.
Enjoy!
using UnityEngine;
public class snapObjToTerrain : MonoBehaviour
{
public Transform objectTransform; // Reference to the player's transform
public float groundClearance = 0.5f; // Offset to place the player above the terrain
public float snapThreshold = 0.1f; // Vertical offset threshold before snapping down
public float smoothTime = 0.3f; // Time it takes to smooth the movement
public float snapSpeed = 5.0f; // Intensity of the snap movement (higher values mean faster snap)
private Vector3 velocity = Vector3.zero;
void LateUpdate()
{
if (Terrain.activeTerrain != null)
{
Vector3 playerPosition = objectTransform.position;
float terrainHeight = Terrain.activeTerrain.SampleHeight(playerPosition);
float targetGroundHeight = terrainHeight + groundClearance;
if (playerPosition.y > targetGroundHeight + snapThreshold)
{
playerPosition.y = Mathf.MoveTowards(playerPosition.y, targetGroundHeight, snapSpeed * Time.deltaTime);
objectTransform.position = playerPosition;
}
else if (playerPosition.y < targetGroundHeight - snapThreshold)
{
// Optional: You can add a check to move the player up to the target height if they're below it
playerPosition.y = Mathf.MoveTowards(playerPosition.y, targetGroundHeight, snapSpeed * Time.deltaTime);
objectTransform.position = playerPosition;
}
}
}
}