Hello folks!
I’ve been doing the Space Shooter tutorial from the Unity tutorials and in the part 1.5 - Moving the Player the author implements boundaries for the space ship. The way he’s done it is by exposing public floats for X and Z range in order to clamp the Player’s rigidbody position with them in FixedUpdate.
The player has a Convex Trigger Mesh Collider (provided by the creator of the series which can be downloaded freely in the asset store) so i wanted to take advantage of that to try a different approach: setting up a Static Box Trigger Collider that surrounds the player effectively marking its moving boundaries. Since they’re trigger colliders, i overrode OnTriggerEnter in a script attached to the boundaries and checked if the Player was the one triggering (checking by its tag). If that happenend, i would then clamp the position of the player just like the tutorial indicated.
This didn’t achieve what i hoped. The results are shown in the GIF i attached to the thread. I would like to detect the collision as soon as the ship hits the box collider.
Side note: For the purposes of the GIF, i set the behaviour of the triggering to reset the player’s position to have a more visual feedback of when OnTriggerEnter is being called.
Here’s the code i’m using for the boundaries:
using UnityEngine;
using System.Collections;
public class BoundariesController : MonoBehaviour {
private float xMin, xMax, zMin, zMax;
void Start() {
Bounds bounds = GetComponent<Collider>().bounds;
xMin = bounds.min.x;
zMin = bounds.min.z;
xMax = bounds.max.x;
zMax = bounds.max.z;
}
void OnTriggerEnter(Collider other) {
if (other.gameObject.CompareTag("Player")) {
Debug.logger.Log("Player collision detected!");
Rigidbody playerRigidbody = other.GetComponent<Rigidbody>();
playerRigidbody.position = new Vector3(
Mathf.Clamp(playerRigidbody.position.x, xMin, xMax),
0.0f,
Mathf.Clamp(playerRigidbody.position.z, zMin, zMax)
);
}
}
}
I hope i was clear enough. I can provide anything extra needed.
Thanks in advance!