- Home /
Other
Door script using Raycast
Im trying to open a door using raycast from a tutorial
here are the scripts ive done so far: interact script: public float interactDistance = 5f;
void Update ()
{
if(Input.GetKeyDown(KeyCode.Mouse0))
Debug.Log("Mouse button was pressed.");
{
Ray ray = new Ray(transform.position, transform.forward);
RaycastHit hit;
if(Physics.Raycast(ray, out hit, interactDistance))
{
if(hit.collider.CompareTag("Door")) //transform
{
hit.collider.transform.parent.GetComponent<DoorScript>().ChangeDoorState();
}
}
}
}
}
Doorscript:
public bool open = false; public float doorOpenAngle = 90f; public float doorCloseAngle = 0f; public float smooth = 2f; //speed door moves
void Start ()
{
}
public void ChangeDoorState()
{
open = !open;
}
void Update ()
{
if (open) // same as open == true
{
Quaternion targetRotation = Quaternion.Euler(0, 0, doorOpenAngle);
transform.localRotation = Quaternion.Slerp(transform.localRotation, targetRotation, smooth * Time.deltaTime);
}
else
{
Quaternion targetRotation2 = Quaternion.Euler(0, 0, doorCloseAngle);
transform.localRotation = Quaternion.Slerp(transform.localRotation, targetRotation2, smooth * Time.deltaTime);
}
}
}
when i get to the door it wont open by clicking on left mouse button but it will suddenly swing open if i look at any of the corners of the door.
Can anyone help with this problem?
Answer by christoph_r · Aug 21, 2017 at 07:01 PM
Your if conditional in line 3 only executes your logging. The raycasting part is actually executed every frame. For conditionals, it's either:
if(bool)
DoStuff();
or:
if(bool)
{
// stuff
}
Mixing the two doesn't work. Your log call needs to be in the brackets.
Thanks for that. When i click on it now it opens and closes but only on the top and bottom of the door.
Follow this Question
Related Questions
Is this way of making a raycast correct 2 Answers
Raycast returns null for no apparent reason 0 Answers
Raycast not hitting instantiated object when timescale is 0 1 Answer
Rigidbody.position causes shaking 1 Answer
Raycast and RaycastHit failure 2 Answers