- Home /
I want to make a tap to "teleport" code.. is this correct?
hye guys, I want to make a 2D racing game that has only 2 lanes. and I want to make the car(player) change its lane every single tap. From right lane, tap! then left lane. From left lane, tap! then right lane.
so this is my code. but compiler says parser error. expecting a close curly braces "{}" at the bottom.. help me guys! :D
void Update ()
{
bool Left = true ;
Touch tap = Input.GetTouch (0);
if (Left == true)
{
if (tap.phase == TouchPhase.Ended && tap.tapCount == 1)
{
transform.Translate (Vector2.right * 5 * Time.deltaTime);
Left = false;
}
}
else if (Left == false)
{
if (tap.phase == TouchPhase.Ended && tap.tapCount == 1)
{
transform.Translate (Vector2.right * -5 * Time.deltaTime);
Left = true;
}
}
}
sorry, but that is the whole script. i just fix the parsing error on line 23.. but i still didnt manage to move my character from left to right and vice versa by a single tap..
This is not the whole script. You are writing in C#. C# scripts always contain a class declaration.
(That's a lie, but if you are still fighting parsing errors you don't need to worry about the details for now)
Answer by CgShady · Oct 05, 2014 at 09:29 PM
A few comments :
"Left" will always be true as it's declared within the Update method and set to true every frame.
You could do :
private bool left = true;
void Update ()
{
Touch tap = Input.GetTouch ( 0 );
if ( tap.phase == TouchPhase.Ended && tap.tapCount == 1 )
{
if ( left )
{
transform.Translate ( Vector2.right * 5 * Time.deltaTime );
}
else
{
transform.Translate ( Vector2.right * -5 * Time.deltaTime );
}
left = !left;
}
}
or even something like this :
private bool _left = true;
public bool Left
{
get { return _left ; }
set
{
if (value != _left)
{
_left = value ;
}
}
}
public float Offset
{
get
{
float offset = Left ? 5 : -5 ;
Left = !Left ;
return offset ;
}
}
void Update ()
{
Touch tap = Input.GetTouch ( 0 );
if ( tap.phase == TouchPhase.Ended && tap.tapCount == 1 )
{
transform.Translate ( Vector2.right * Offset * Time.deltaTime );
}
}
Sorry, I didn't read your question to the end, yes you probably miss a closing } at the end. The ending bracket of your code matches the Update Opening bracket. You need one to close the Class.
thank you cg shady, but when i type in your code.. why does the private and public get red squigy line? (like when you mispelled something in ms word).
public and private have to be outside any method. That's why he is declaring private bool left = true;
right before Update, outside of it.
Your answer
Follow this Question
Related Questions
Differentiating a tap from a swipe? 1 Answer
Single Tap Registered on Swipe (C#) 0 Answers
codes for detecting mobile double tap and hold 1 Answer
touch game objects on ios 1 Answer