I am trying to make it so that certain platforms can only be collided with when the mouse is near/on these platforms. When I play the game it plays like it would without the script. Does anyone know a way I can fix the script to do so?
public class PositivePlatform : MonoBehaviour {
// Use this for initialization
void Start () {
gameObject.SetActive (true);
{
if (Input.GetKey (KeyCode.Mouse1))
;
}
}
This code assumes that its in a script on your platform GameObject that you want to enable when clicked.
private bool allowCollision;
void Update()
{
Ray ray = Camera.main.ScreenPointToRay (Input.mousePosition);
RaycastHit hit;
GetComponent<Collider>().enabled = true;
if (Input.GetMouseButtonUp(0) && Physics.Raycast(ray, out hit))
{
if (hit.collider.gameObject == gameObject)
allowCollision = true;
}
GetComponent<Collider>().enabled = allowCollision;
}
To explain it. We create a ray, that uses the current camera and the mouse screen coordinates. Now to actually allow a raycast to register a hit with our collider, we need to enable it first.
If the uses pressed the left mouse button, we make a raycast check against our scene with our created ray. If the found collider is attached to our own gameobject, we allow the collider to stay active, otherwise we disable it directly again.
This is a quick and dirty solution, it would be propably nicer to work with collision layers.