Reputation: 115
I made a mobile 2D game in which you need to tap the screen to start moving the ball but something went wrong. This is my code:
void Start ()
{
if (Input.touchCount >=1)
{
GetComponent<Rigidbody2D> ().AddForce (new Vector2 (1f, 0.5f) * force);
}
When I tap the screen, the ball is still fixed.
Upvotes: 1
Views: 4304
Reputation: 1076
Your code doesn't work because you are checking input count in Start method. Start method is called when Scene is created. After that it will not check your if statement. Write it into Update method like this.
bool started = false;
void Update()
{
if (Input.touchCount >=1 && !started)
{
GetComponent<Rigidbody2D> ().AddForce (new Vector2 (1f, 0.5f) * force);
started=true;
}
}
Upvotes: 1
Reputation: 843
As mentioned you used the code on Start method. If you want to use the touch to move the ball only one time, use a bool perhaps. Declare this:
public class movingBall : MonoBehaviour {
bool gameStart;
void Start(){
gameStart=false;
}
void Update()
{
if (Input.touchCount >=1)
{
if (gameStart){
//game already started, do stuff with touch action in game
}else{
//game not started yet, move the ball once
gameStart=true;
GetComponent<Rigidbody2D> ().AddForce (new Vector2 (1f, 0.5f) * force);
}
}
}
}
For a game over, just remember to set it false again.
If you gonna use the touch input ONLY for start you can do like:
public class movingBall : MonoBehaviour {
bool gameStart;
void Start(){
gameStart=false;
}
void Update()
{
if (!gameStart){
if (Input.touchCount >=1) {
gameStart=true;
GetComponent<Rigidbody2D> ().AddForce (new Vector2 (1f, 0.5f) * force);
}
}
}
}
Upvotes: 1
Reputation: 1359
Modifying ゴスエン ヘンリ's answer.
public class movingBall : MonoBehaviour {
bool _gameStarted = false; // In the class but outside any function
void Update()
{
if (!_gameStarted ){
if (Input.GetMouseButtonDown(0)){ // It will work on mobile too.
_gameStarted = true;
GetComponent<Rigidbody2D> ().AddForce (new Vector2 (1f, 0.5f) * force);
}
}
}
}
Upvotes: 0