- Home /
Flipping a 2D Game object over time
I've created a platform for a 2D platformer that has spikes on the bottom and is safe on the top. I want to flip the Game object on the Y axis every few seconds, flipping the box collider along with it. What's the best way of doing this? The only ways I've found out so far are from making the object move up and down but I would like it to stay still
Thank you :)
I don't know if it is the best solution, but it should work: set the scale to -1
public GameObject spike;
public int timer = 2;
int spikeY = 1;
void Start(){
InvokeRepeating("flip",timer, timer);
}
void flip(){
spikeY *= -1;
Vector3 newScale = new Vector3(1,spikeY,1);
spike.transform.localScale = newScale;
}
Answer by The-Peaceful · Apr 30, 2021 at 07:45 AM
You can either go with the approach that @DevManuel commented or, instead of scaling, rotate the sprite over the X axis, like so:
public float timer = 2;
void Start(){
InvokeRepeating("Flip",timer, timer); //Execute method every 'timer' seconds
}
void Flip() {
transform.Rotate(new Vector3(180f, 0)); //Rotate 180 degrees over the X axis to flip it over the Y axis
}
//Or like this
private float counter = 0;
public float timer = 2f;
void Update(){
if(counter >= timer){
transform.Rotate(new Vector3(180f, 0));
}
counter += Time.deltaTime;
}
Whatever you like best :D Also make sure that your pivot is set up correctly (at the point that you want to flip your sprite over) else it won't stay in place with neither the scaling nor the rotation option. Hope it helps :P
https://docs.unity3d.com/ScriptReference/MonoBehaviour.InvokeRepeating.html
Used the first one and it worked perfectly, thank you so much! :)
Your answer
Follow this Question
Related Questions
I cant get wall jumping to work in my 2D platformer (C#) 1 Answer
Multiple Cars not working 1 Answer
Boss Health Bar 1 Answer
Jumping from special jump orb 1 Answer
While Moving Left or Right my character falls more slowly. 2 Answers