- Home /
Trigger Event with Pressing on a Mesh
Hey guys!
I just have a quick question. I have a small script that allows the player to enter a car. nothing special. it uses an empty game object with a Cube (Mesh Filter) and if the player is running around in this Mesh and presses "F" he will enter the car. Buuuut, I want to use this script for mobile and as you all know that there is no "F" button on the iphone.
So, my idea is, that you have to tap on the Cube to enter the car instead of pressing "F" currently the script is working like that (javascript):
function Update()
{
if (Input.GetKeyUp("f")&& isPlayerVisible) //Asign any key you want to enter/operate vehicle.
{
Debug.Log("Driving");
so, how can i replace the Input.GetKeyUp("f") with something like Press.GameObject("EnterCar") or how ever this will work?
Thanks in advance! Kev!
Answer by Zaeran · Nov 02, 2013 at 02:55 PM
Camera.main.ScreenPointToRay(ScreenTouchPosition)
will give you a ray pointing through the camera to the position touched on the screen.
Pass the ray into a raycast, then analyse what gets hit. If it's the car, then get in.
Relevant code:
Ray screenRay = Camera.main.ScreenPointToRay(ScreenTouchPosition);
RaycastHit rayhit;
if(Physics.Raycast(screenRay, out rayhit)){
if(rayhit.collider.tag == "CarCube"){ //whatever you want to call it
Debug.Log("Driving");
}
}
Hey, thanks a lot :) i just have some questions, just to understand the code and learn from that :)
so, Camera.main is always the Camera? even if my Camera has the Name "tk2dCamera_Player" but its still Tagged as main camera?
and, (ScreenTouchPosition): am I still able to test the scene within the unity player even if the game is not already on my phone or should i change it to something like (Screen$$anonymous$$ousePosition) when i want to test it with my mouse cursor?
and, "CarCube" is the name of the GameObject right? so in my case it would be "doorTriggerLeft" but i just have to replace it ere right?
Thanks a lot!
Camera.main is whichever camera is tagged as $$anonymous$$ainCamera, regardless of the name.
As far as I know, Unity doesn't have any built in method to test touches, so you'll probably have to use Screen$$anonymous$$ousePosition.
You're correct. CarCube is the name of the object, and you replace it with the name of the object you want to click on
Answer by Der_Kevin · Nov 03, 2013 at 07:03 PM
ok, thanks, one more ;) now the code looks like this:
function Update()
{
Ray screenRay = Camera.main.ScreenPointToRay(ScreenTouchPosition);
RaycastHit rayhit;
if(Physics.Raycast(screenRay, out rayhit)){
if(rayhit.collider.tag == "doorTriggerLeft")
{
Debug.Log("Driving");
but unity says "Assets/Standard Assets/Scripts/Car entering & exiting.js(16,4): UCE0001: ';' expected. Insert a semicolon at the end."
16,4 is between Ray and screenRay could you help me with that? :)
Your answer
