- Home /
Ray cast affects all colliders in scene if mouse button is not releasesd.
To be specific i have some drawers in my scene and i want to open-close them by click and drag them to open-close. Each drawer has a collider atached. When i hit the first drawer it opens-closes corectlly but before i release the mouse button and move the mouse pointer over another drawer or all drawers in scene, all of them starts to open at once.
What i want is to click a drawer and drag it to open-close it, the click another one and so on. I know that a way to do this is by using tags or layers but i am not very good at scripting yet.
Here is the code.
public GameObject drawer;
void Update () {
if (Input.GetMouseButton(0)) {
RaycastHit hit;
Ray ray = Camera.main.ScreenPointToRay (Input.mousePosition);
if (Physics.Raycast (ray, out hit, 100.0f)) {
drawer = hit.collider.gameObject;
}
if (drawer != null ) {
translate_z += Input.GetAxis ("Mouse Y") * sensX * Time.deltaTime;
translate_z += Input.GetAxis ("Mouse X") * sensX * Time.deltaTime;
translate_z = Mathf.Clamp (translate_z, -1.25f, 0.0f);
drawer.transform.localPosition = new Vector3 (0.0f, 0.0f, translate_z);
}
} else {
//drawer = null;
}
}
Answer by getyour411 · Dec 09, 2016 at 04:38 AM
I think you want something like
4: if inputgetmouse && !isDragging (new bool)
11.5/newline isDraggging = true;
19.5/newline if(input.getmouseup) isDragging = false
Something to capture the state of dragging and only do stuff when you aren't dragging.
Thanks man for your answer. I adjusted my code as you mention and now it works great.
Here is the corrected code.
using UnityEngine;
using System.Collections;
public class draw : $$anonymous$$onoBehaviour {
float translate_z;
float translate_new_z;
float sensX = 2.0f;
public GameObject drawer;
public bool isDraging;
void Update () {
if (Input.Get$$anonymous$$ouseButton (0)) {
if (!isDraging) {
RaycastHit hit;
Ray ray = Camera.main.ScreenPointToRay (Input.mousePosition);
if (Physics.Raycast (ray, out hit, 100.0f)) {
drawer = hit.collider.gameObject;
isDraging = true;
}
}
if (isDraging) {
translate_z += Input.GetAxis ("$$anonymous$$ouse Y") * sensX * Time.deltaTime;
translate_z += Input.GetAxis ("$$anonymous$$ouse X") * sensX * Time.deltaTime;
translate_z = $$anonymous$$athf.Clamp (translate_z, -1.25f, 0.0f);
drawer.transform.localPosition = new Vector3 (0.0f, 0.0f, translate_z);
translate_new_z = drawer.transform.localPosition.z;
Debug.Log (translate_new_z);
}
} else if (Input.Get$$anonymous$$ouseButtonUp(0)) {
isDraging = false;
}
}
}