- Home /
Left Click and Right Click Ray-casting.(C#)
I'm trying to make a simple game and was experimenting with ray-cast. If you are skilled with this I would be happy if you can help. Anyway, i'm trying to make it so I can set an object (Munchkin) active when left clicked and when right clicked on another object (DogBed) it will then return set active to nothing, the whole half of my script is ignored.. If you can help please do. - LL
Here is the code:
using UnityEngine;
using System.Collections;
public class PickUpMunchkin : MonoBehaviour {
public GameObject FPMunchkin;
RaycastHit hit; //Set up the Raycast hit
void Update ()
{
Vector3 fwd = transform.TransformDirection(Vector3.forward); //the direction the player is facing
if (Input.GetMouseButtonDown(0))
{
if (Physics.Raycast(transform.position, fwd, out hit, 5)) //If Munchkin is in front of player but within 5 units of the ray (Hit)
{
if(hit.transform.gameObject.tag == "Munchkin") //Check if Munchkin is there
{
Destroy(hit.transform.gameObject); //Destry scene munchkin
FPMunchkin.SetActive(true);
Debug.Log("It Works 1st Part");
}
if (Input.GetMouseButtonDown(1))
{
if (Physics.Raycast(transform.position, fwd, out hit, 5))
{
if(hit.transform.gameObject.tag == "DogBed")
{
FPMunchkin.SetActive(false);
Debug.Log("It Works 2nd Part");
}
}
}
}
}
}
}
Answer by Kiwasi · Nov 17, 2014 at 12:51 AM
The {} are all wrong. The right button if is nested inside the left button if.
Note that GetButtonDown will only return true once, when the button is pushed down. So for the second part of the code to be executed both buttons must be pressed down in the same frame. At 60 fps this is a pretty challenging task.
Thank you so much! Wow I feel stupid to make that mistake. Thank you -LL
Answer by rob5300 · Nov 16, 2014 at 11:05 PM
Looking at your code, it should work, but to be sure you can:
Make sure there is an 3d collider on the objects. For 2d use Raycast2d. That should be from the Physics2d class.
Try using the transform of the main camera instead of the player object as it will of forward from the axis origin which may be below the camera view.
Increase the reach distance.
Try using Debug.Drawray to see in the scene view where the ray really goes.
Well I took your advice into consideration, Thanks and I found out the problem was that the second part of the code (the right click) doesn't run. If you know why please help.
Your answer
Follow this Question
Related Questions
Inventory GUI 0 Answers
Perspective issue with railgun/raycasting 0 Answers
Prevent Raycast on reacting to GUI input? 2 Answers
Why Raycast is not working properly? 0 Answers