Last active
November 7, 2017 20:13
-
-
Save BoraxKid/4b356108780ab7a8b69db4d278eae5c5 to your computer and use it in GitHub Desktop.
Rotating Platform
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 Rotate : MonoBehaviour | |
{ | |
// Rotation value | |
// The [SerializeField] make it visible in the editor even though it is private | |
[SerializeField] private Vector3 _rotation = Vector3.zero; | |
// The list of all the GameObjects attached to the platform | |
private List<GameObject> _attachedObjects = new List<GameObject>(); | |
// When a GameObject stays in collision | |
// Check if it is on top of the platform | |
// And add it to the list and set the parent accordingly | |
private void OnCollisionStay(Collision collisionInfo) { | |
// We don't want to add the GameObject to the list if is it already attached to the platform | |
if (this._attachedObjects.Contains(collisionInfo.gameObject)) { | |
return; | |
} | |
else { | |
// We check every contact point of the collision | |
// This ensure that if a GameObject is only half on the platform, it still works | |
foreach (ContactPoint contactPoint in collisionInfo.contacts) { | |
// If the point is on top of the platform | |
// We add it to the list | |
// And we set its parent to be the platform | |
if (contactPoint.point.y > this.transform.position.y) { | |
this._attachedObjects.Add(collisionInfo.gameObject); | |
collisionInfo.transform.SetParent(this.transform); | |
return; | |
} | |
} | |
} | |
} | |
// When a GameObject exits the collision with the platform | |
// Remove it from the list and unparent it (if it was in the list) | |
private void OnCollisionExit(Collision collisionInfo) { | |
// Check if the object was in the list | |
if (this._attachedObjects.Contains(collisionInfo.gameObject)) { | |
// Yes ? good, then unparent it | |
collisionInfo.transform.SetParent(null); | |
// And finally remove it from the list | |
this._attachedObjects.Remove(collisionInfo.gameObject); | |
} | |
} | |
void Update() { | |
// Rotate the platform every frame | |
this.transform.Rotate(this._rotation * Time.deltaTime); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Unity C# script
Used for rotating a platform and making the GameObjects on top of it following its movement.
What this script does: