Skip to content

Instantly share code, notes, and snippets.

@unity3dcollege
Created March 1, 2019 23:06
Show Gist options
  • Save unity3dcollege/6ec023da2d9d35f5cde8050246b52c90 to your computer and use it in GitHub Desktop.
Save unity3dcollege/6ec023da2d9d35f5cde8050246b52c90 to your computer and use it in GitHub Desktop.
private void StickToMovingObjects()
{
if(groundedObj != null){
if(groundedObjLastPosition.HasValue &&
groundedObjLastPosition.Value != groundedObj.position){
//Determines the delta of the last position to the new position.
Vector3 delta = groundedObj.position - groundedObjLastPosition.Value;
//Moves the grounded object at the same rate as the groundedObj.
GetComponent<Rigidbody2D>().position += (Vector2)delta;
}
//Updates last position of grounded object.
groundedObjLastPosition = groundedObj.position;
} else {
//If there is no grounded object, set the last position to null to prevent unusual behavior.
groundedObjLastPosition = null;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment