- Home /
Collision detection issue
Hey, I am a total newbie when it comes to unity and coding and I'm trying to make a frogger type game. I'm having trouble with my player not detecting vehicles, and I can't seem to find a solution. It was working before I started to mess with the water, but even after un-doing all that, it still doesn't work.
Thanks in advance for any help!
void Update()
{
if (playerIsAlive == true)
{
x = Input.GetAxis("Horizontal");
y = Input.GetAxis("Vertical");
if (x != 0 || y != 0)
{
if (!isWalking)
{
isWalking = true;
anim.SetBool("isWalking", isWalking);
}
Move();
}
else
{
if (isWalking)
{
isWalking = false;
anim.SetBool("isWalking", isWalking);
}
}
}
}
void LateUpdate()
{
if(playerIsAlive == true)
{
if (isInWater == true && isOnPlatform == false)
{
KillPlayer();
}
}
}
private void Move()
{
if (playerIsAlive == true)
{
anim.SetFloat("x", x);
anim.SetFloat("y", y);
transform.Translate(x * Time.deltaTime * moveSpeed, y * Time.deltaTime * moveSpeed, 0);
}
}
private void OnTriggerEnter2D(Collider2D collision)
{
if(collision.transform.GetComponent<Vehicle>() != null)
{
KillPlayer();
print("hit");
}
else if (collision.transform.GetComponent<Platform>() != null)
{
transform.SetParent(collision.transform);
isOnPlatform = true;
}
else if (collision.transform.tag == "Coin")
{
playerCanMove = false;
}
else if (collision.transform.tag == "Water")
{
isInWater = true;
GetComponent<AudioSource>().PlayOneShot(drownNoise);
}
}
void OnTriggerExit2D(Collider2D collision)
{
if (playerIsAlive == true)
{
if (collision.transform.GetComponent<Platform>() != null)
{
transform.SetParent(null);
isOnPlatform = false;
}
else if (collision.transform.tag == "Water")
{
isInWater = false;
}
}
}
void KillPlayer()
{
playerIsAlive = false;
playerCanMove = false;
isWalking = false;
GetComponent<SpriteRenderer>().sprite = deadSprite;
}
Hi, did you debug whether your OnTriggerEnter methods are being called? Also, Unity has very strict rules about what can trigger what. Have a look at the table at the bottom of this manual. If the functions aren't being called, its very likely a mismatch between Collider and Rigidbody components
Does your player has rigidbody? Are your vehicles colliders "isTrigger" enabled?
Answer by CycloneWhale · Aug 24, 2021 at 12:40 AM
You have to make sure that your player and any objects you want it to collide with have a 2D collider set to "IsTrigger" and also have a Rigidbody2D component.
Your answer
Follow this Question
Related Questions
Why can't I destroy this object!? 3 Answers
Best way to manually calculate collision between GameObjects and a Tilemap without using physics 1 Answer
Unity2D: How to make my player not walk through walls? 1 Answer
Sprites collision not working on high speeds 1 Answer
Can't detect colliders from Tiled 0 Answers