OnCollisionEnter2D Not Working. Objects Triggering without being selected.
I am moving the Player object to the Square object, and it does not collide (both have box colliders2d's and rigidbody2d's). Neither works the OnCollisionEnter2D function. What i'm trying to do is that when the player collide with the square, the square change his position.
Player code:
public class Control : MonoBehaviour
{
[SerializeField]
GameObject _player;
GameObject _square;
[SerializeField]
Rigidbody2D player;
float r1, r2;
float speed;
Vector3 movement;
void Start()
{
speed = 5;
Cursor.lockState = CursorLockMode.Confined;
player = GetComponent<Rigidbody2D>();
}
void Update()
{
if (Input.GetMouseButtonDown(0))
{
Vector2 mousepos = new Vector2(Input.mousePosition.x, Input.mousePosition.y);
Vector2 worldPosition = Camera.main.ScreenToWorldPoint(mousepos);
_player.transform.position = worldPosition;
}
float moveHorizontal = Input.GetAxisRaw("Horizontal");
float moveVertical = Input.GetAxisRaw("Vertical");
movement = new Vector3(moveHorizontal, moveVertical, 0f);
movement = movement * speed * Time.deltaTime;
transform.position += movement;
}
void OnCollisionEnter2D(Collision2D coll)
{
Debug.Log("e");
if (coll.gameObject.tag == "Enemy")
{
Debug.Log(".e.e.eleldlelñde");
r1 = Random.Range(-8.27f, 8.15f);
r2 = Random.Range(4.35f, -4.45f);
_square = GameObject.FindGameObjectWithTag("Enemy");
_square.transform.position = new Vector3(r1, r2, 0);
}
}
}
Square code:
public class SquareScript : MonoBehaviour
{
[SerializeField]
public GameObject _square;
float r1, r2;
void Start()
{
r1 = Random.Range(-8.27f, 8.15f);
r2 = Random.Range(4.35f,-4.45f);
//_square = GetComponent<GameObject>();
_square.transform.position = new Vector3(r1,r2,0);
}
void Update()
{
}
void OnCollisionEnter2D(Collision2D coll)
{
Debug.Log("e");
if (coll.gameObject.tag == "Enemy")
{
Debug.Log(".e.e.eleldlelñde");
r1 = Random.Range(-8.27f, 8.15f);
r2 = Random.Range(4.35f, -4.45f);
_square = GameObject.FindGameObjectWithTag("Enemy");
_square.transform.position = new Vector3(r1, r2, 0);
}
}
}
annotation-2020-05-12-221504.png
(70.5 kB)
annotation-2020-05-12-221523.png
(74.1 kB)
Comment
Your answer
![](https://koobas.hobune.stream/wayback/20220612234126im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Navmesh agents not colliding with non trigger colliders? 0 Answers
Why won't this object destroy on collision? 1 Answer
why isnt my code working, 2 Answers
Mesh collider 0 Answers
ANIMATION TRIGGER DOESN'T PLAY 1 Answer