- Home /
trying to reverse 2D player's gravity after colliding with specific object
hey, I'm new to unity and not very sure about what I'm doing. I got the rotate() method from youtube but can't actually reverse the player's gravity when they collide with the 'potion'.. Help please?
This is my code so far -
private bool top;
private Rigidbody2D rb;
void Start()
{
rb = GetComponent<Rigidbody2D>();
}
void OnTriggerEnter2D (Collider2D col)
{
if(col.gameObject.tag == "potion")
{
rb.gravityScale *= -1;
rotate();
}
}
void rotate()
{
if(top == false)
{
transform.eulerAngles = new Vector3(0,0, 180f);
} else {
transform.eulerAngles = Vector3.zero;
}
top = !top;
}
}
Answer by N-8-D-e-v · Sep 03, 2020 at 12:51 PM
This looks pretty good so far, just something picky though, in c# we use the Pascal Naming Convention to name methods and classes, so for best practice, rename
void rotate()
to
void Rotate()
(Although this is not necessary for your code to run properly) As for your original question, is the tag of your potion have its collider marked as a trigger? And is its tag "potion", or "Potion"? Because it is case sensitive. Also, make sure you have assigned a tag to the potion gameobject. Finally, you can throw a little
Debug.Log(col.name + " " + col.tag);
So you can figure out what is actually colliding with your trigger
thanks but this code isn't working for me still, I have the potion's box collider ticked as 'is Trigger' and made sure the p was common in the tag. I also added the console message and that's not even showing up ..
edit - I used gameObject.name instead of gameObject.tag since I'll only use this effect for this certain object, it works now :0
if you want to use tag, try if (col.CompareTag("Potion")