Reputation: 1214
My gameobjects are moving oddly.
On the enemy, I have this script :
public float speed = 1.0f;
private Transform target;
public void Start()
{
var player = GameObject.FindWithTag("Player");
target = player.transform;
}
void Update()
{
// Move our position a step closer to the target.
float step = speed * Time.deltaTime; // calculate distance to move
transform.position = Vector3.MoveTowards(transform.position, target.position, step);
// Check if the position of the cube and sphere are approximately equal.
if (Vector3.Distance(transform.position, target.position) < 0.001f)
{
// Swap the position of the cylinder.
target.position *= -1.0f;
}
}
After I hit the enemy with a projectile, it starts moving slower. The script behind the projectile is this :
if (coll.gameObject.tag != "Player")
{
Destroy(gameObject);
if ((coll.collider.GetComponent("Damageable") as Damageable) != null)
{
var d = coll.collider.GetComponent<Damageable>();
d.Damage(1);
}
}
I added this script in, as a Damageable component, however, this behavior was there even before this script was active, so I don't think it's related :
public void Damage(int damageAmount)
{
print("Damage : " + Health + ":" + damageAmount);
Health -= damageAmount;
if (Health <= 0)
{
Destroy(gameObject);
}
}
Any recommendations on what is wrong?
Upvotes: 0
Views: 76
Reputation: 27086
coll
I guess this is short for collision, collision happens on 2 rigidbodies (or another static collider, but unrelated to the question), so when the bullet hit the enemy, it also block the enemy's path, even if you destroy it immediately the enemy will still stop moving for 1 frame.
So make the collider on the bullet to be a trigger, a trigger won't block other rigidbodies.
Use OnTriggerEnter2D
(or OnTriggerEnter(Collider)
for 3D game) to receive touch event.
void OnTriggerEnter2D(Collider2D other)
{
if (other.gameObject.tag != "Player")
{
Destroy(gameObject);
var d = other.GetComponent<Damageable>();
if(d != null)
d.Damage(1);
}
}
Upvotes: 1