- Home /
Collision Detection Between Instances of Prefabs doesn't work
I have a problem, that may have a simple solution. I'm making a 2D game and I have enemies that spawn and follow a player. Everything works fine, except that when 2 enemies should "repel" each other they just overlap.
I have a script with the AI and I'm manipulating the rigidbodies to move the enemies because I read that it should fix the problem, but it didn't.
Here is the AI code
using UnityEngine;
using System.Collections;
public class StFleetAI : MonoBehaviour {
Transform target;
public float rotationSpeed;
Transform myTransform;
void Start()
{
myTransform = transform;
}
void RotateToPlayer()
{
float x = target.position.x - myTransform.position.x;
float y = target.position.y - myTransform.position.y;
float angle = Mathf.Atan2(x, y) * Mathf.Rad2Deg;
Quaternion q = Quaternion.Euler(0,0,-angle);
myTransform.rotation = Quaternion.Slerp(myTransform.rotation,q, rotationSpeed*Time.deltaTime);
}
void Update () {
target = GameObject.FindWithTag("Player").transform;
RotateToPlayer();
rigidbody2D.AddRelativeForce(new Vector2(0,2500));
restrictMovement();
}
void restrictMovement()
{
if (transform.position.x <= -830) {
transform.position = new Vector3(-830, transform.position.y, transform.position.z);
} else if (transform.position.x >= 830) {
transform.position = new Vector3(830, transform.position.y, transform.position.z);
}
if (transform.position.y <= -535) {
transform.position = new Vector3(transform.position.x, -535, transform.position.z);
} else if (transform.position.y >= 535) {
transform.position = new Vector3(transform.position.x, 535, transform.position.z);
}
}
}
Here is the enemy's setup
I'm not sure if the physics engine works the collisions automatically or if I should use a separate algorithm.
Any help would be awesome, thanks!
I don't know if this will work but maybe your moving your objects with a translate function, which means that it will overwrite the physics engine, therefore it will look messy.
Answer by d2 · Mar 04, 2015 at 09:47 PM
The isTrigger has to be unchecked.
i also recommend you, to use FixedUpdate is$$anonymous$$d of update for the physics
Your answer
Follow this Question
Related Questions
Keeping player stationary and let physics affect... 0 Answers
Continuous collision detection - unnatural behaviour 0 Answers
Handling colliders on hundreds of asteroids (not procedural asteroids) ...URGENT 3 Answers
Can I change the order that collision layers collide with each other? 1 Answer
Is there anyway to see if another Object has any Collision? 1 Answer