Created
December 28, 2018 15:05
-
-
Save jeffvella/aff34cd846198b580803d990e7686734 to your computer and use it in GitHub Desktop.
Attach an object to a platform when they collide and move with it.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.Collections; | |
using System.Collections.Generic; | |
using UnityEngine; | |
public class SnapToPlatform : MonoBehaviour | |
{ | |
private Vector3 _lastPlatformPosition; | |
private Quaternion _lastPlatformRotation; | |
public bool IsOnPlatform; | |
public GameObject CurrentPlatform; | |
public string PlatformLayerName = "Platform"; | |
void Awake() | |
{ | |
IsOnPlatform = false; | |
} | |
void OnCollisionEnter(Collision collision) | |
{ | |
foreach (ContactPoint contact in collision.contacts) | |
{ | |
if (contact.otherCollider.gameObject.layer == LayerMask.NameToLayer(PlatformLayerName)) | |
{ | |
IsOnPlatform = true; | |
CurrentPlatform = contact.otherCollider.gameObject; | |
} | |
} | |
} | |
void OnCollisionExit(Collision collision) | |
{ | |
if (collision.gameObject == CurrentPlatform) | |
{ | |
IsOnPlatform = false; | |
CurrentPlatform = null; | |
} | |
} | |
void Update() | |
{ | |
if (IsOnPlatform) | |
{ | |
var currentPlatformPosition = CurrentPlatform.transform.position; | |
var currentPlatformRotation = CurrentPlatform.transform.rotation; | |
if (currentPlatformRotation != _lastPlatformRotation) | |
{ | |
var rotationChange = Quaternion.Inverse(_lastPlatformRotation) * currentPlatformRotation; | |
transform.rotation = transform.rotation * rotationChange; | |
} | |
if (currentPlatformPosition != _lastPlatformPosition) | |
{ | |
var positionChange = currentPlatformPosition - _lastPlatformPosition; | |
transform.position += positionChange; | |
} | |
_lastPlatformPosition = CurrentPlatform.transform.position; | |
_lastPlatformRotation = CurrentPlatform.transform.rotation; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment