Im making a pong game with power-ups what i want to happen is that when the ball hits the power up the float speed increases by 5 for 10 seconds or until a point is scored but whats happening is that the speed increases by 5 after a point is scored not immdiately when its hit heres my code
using UnityEngine;
using System.Collections;
public class PowerUp : MonoBehaviour {
static bool trip = false;
void OnCollisionEnter2D(Collision2D other){
if(other.gameObject.tag=="ball"&&!trip){
trip=true;//stop collision from running twice
ballControl.speed+=10;
StartCoroutine(speedtime());
GetComponent<SpriteRenderer>().enabled=false;
}
}
IEnumerator speedtime(){
yield return new WaitForSeconds (1);
revertSpeed();
Destroy (gameObject);
}
void revertSpeed(){
ballControl.speed = 5;
}
}
Hello,
I dont know if that’s what you need but since it’s some kind of power up then use triggers instead of collisions:
void OnTriggerEnter2D(Collider2D col) //so that the ball will not bounce off
Second thig is when it hits this trigger you should start counting:
float someTime;
bool PowerUp = false;
public void Update(){
if(PowerUP){
someTime += Time.deltaTime
if(someTime >= 10.0f) PowerUP = false;
}
}
In the OnTriggerEnter2D method just simply change this values like so:
if(col.tag == "PowerUP"){
someTime = 0;
PowerUP = true;
}
Regards,
M.Rogalski
ok i did i reworked my code but now i’ve run into another problem when it hits the powerUp it doesn’t immediately take effect it waits until after a point has been scored to work here my on trigger code
void OnTriggerEnter2D(Collider2D col){
if (col.gameObject.tag == "Pickup") {
SetBallSpeed(speed*2);
Destroy(col.gameObject);
}
}