Hey! I am trying to make a maze game.
My goal is to make the player go to the initial position if he touched the walls.
please make my code better
Here is my code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class collision : MonoBehaviour
{
Rigidbody2D rb;
void Start()
{
}
private void OnTriggerEnter2D(Collider2D collision)
{
transform.position = new Vector2(x: -21, y: -9);
Debug.Log("Triggered");
}
}
its very simple, thats why it doesnt work
I assume this “collision” script is attached to the walls that you discuss within your post. If that is the case then transform.position will change the position of the wall rather than the player. To get access to the colliding player object you will need to do something such as…
collision.gameObject.transform.position = new Vector2(-21, -9);
This line of code gets a reference to the colliding object, and then gets the transform and then it’s position, finally setting it to the new Vector2.
Uh… if this is attached to the wall then why is there a rigidbody2d…?
And you might want to do some if statements to check if you actually collided with the player/wall (depending on what the script is attached to.