Skip to content

Instantly share code, notes, and snippets.

@bahadir
Last active May 18, 2018 07:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bahadir/01f27e4672eb7777974878c341228cfe to your computer and use it in GitHub Desktop.
Save bahadir/01f27e4672eb7777974878c341228cfe to your computer and use it in GitHub Desktop.
Sliding objects along colliding walls
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MoveCube : MonoBehaviour {
private Rigidbody rb;
private Dictionary<GameObject, Vector3> walls = new Dictionary<GameObject, Vector3>();
void OnCollisionEnter(Collision other) {
walls.Add(other.gameObject, other.contacts[0].normal);
}
void OnCollisionExit(Collision other) {
walls.Remove(other.gameObject);
}
void Start() {
rb = GetComponent<Rigidbody>();
}
void Update () {
// Replace this with your input code
Vector3 movement = new Vector3(5, rb.velocity.y, -5f);
foreach (var w in walls) {
if (Vector3.Angle(movement, w.Value) > 90) {
movement = Vector3.ProjectOnPlane(movement, w.Value);
}
}
rb.velocity = movement;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment