- Home /
Mouse Click to keyCode
ok, in first step sorry for my bad en:D
So, i trying to make a 2d game, for android and i make a car, wich i need to move left and writh ....so
i made, with this code:
var leftKey : KeyCode;
var rightKey : KeyCode;
var speed : float = 15;
function Update ()
{
if (Input.GetKey(rightKey))
{
rigidbody2D.velocity.x = speed;
}
else if (Input.GetKey(leftKey))
{
rigidbody2D.velocity.x = speed *-1;
}
else
{
rigidbody2D.velocity.x = 0;
}
}
but i can`t move this car left and right with A and D or any buttons .....
BUT...
i need to move this car with my touch screen so, what i made it for that...i create to objects, for 1/2 of screen (left and right bottons)....
my menu work good with this code
function OnMouseUp()
and i try and i try but i don`t know how to connect this function...becouse are two differit commponet of two differit objects.....so i stuck HERE....
it`s exist any ideea to put that fucion "OnMouseUp" to simulate a "A" or another keycode...to move my car?
Thank You:)
SORRY FOR THIS VERY BAD EN!!!
Answer by CodeElemental · Feb 20, 2014 at 11:30 AM
Maybe you can use
Input.GetTouch(0).position;
and then check for whether X is on the left/right side of the screen ?
void Update()
{
if (Input.touchCount > 0)
{
if (Input.GetTouch(0).position.x < halfX)
{
// Move left.
} else if (Input.GetTouch(0).position.x > halfX)
{
// Move right
} else
{
// reset movement.
}
} else
{
// reset movement.
}
}
this code is for my car? becouse i add this code in a componet of my car and i got this error
Assets/move.cs(1,6): error CS0116: A namespace can only contain types and namespace declarations
$$anonymous$$y best guess is you have some errors in the brackets. Also, (since you wrote your code snippet in javascript) this code is in C# you may want to convert it to javascript.
Find out more here
From the error line number (1,6) i think you're missing
using UnityEngine;
so i put this cod for my car
function Update()
{
if (Input.touchCount > 0)
{
if (Input.GetTouch(0).position.x < 2.5)
{
rigidbody2D.velocity.x = -10;
} else if (Input.GetTouch(0).position.y > 2.5)
{
rigidbody2D.velocity.x = 10;
} else
{
}
} else
{
rigidbody2D.velocity.x = 0;
}
but my car go just in the right :( anywhere i touch my screen
position The position of the touch in pixel coordinates.
from the unity Documentation. I think that halfX should be half of the screen width ( in pixels ) ex. if the width is 400 it should be 200.
also the second check is wrong.
else if (Input.GetTouch(0).position.y > 2.5)
why check for y value? Is this desired?
Your answer
![](https://koobas.hobune.stream/wayback/20220613134103im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Sidescroller Bullets Follow Mouse After Being Shot 2 Answers
2d camera help! 0 Answers
Mouse as a throttle 1 Answer
Changing material orientation dependant on mouse location? 0 Answers
What do I type so that integers interact with the animator. 0 Answers