I have a script that makes the AI shoot at the current Player position. The part that works, is that he shoots at the Player. But the speed of the bullet isnt always the same … and for some reason I cant get, how it should be. Well this is how I calculate the speed:
target = GameObject.FindGameObjectWithTag(“Player”).transform;
direction = (target.position - transform.position).normalized;
direction = direction * speed * Time.deltaTime;
So its pretty simple, first I find the Player, then I calculate the vector between the Player and the Enemy that is shooting, and then I normalize it, so that I can give it the desired speed.
The Problem is, sometimes the bullet is really really slow, and sometimes its normal.
I added Debug.Log(direction) and it told me numbers like this:
(-0.2, 0)
(0.4, 0)
(-0.2, 0)
(0.2, 0)
(0, 0) ← yes the bullet had no speed at all o.O
(-0.2, 0.1)
(0, 0,2)
These numbers dont make sense to me. Shouldnt the x and the y add up to a specific value?
If there is something that I should show tell me I hope this isnt too long or to easy
Thanks for helping me in advance
because target.position - transform.position
will not be the same depending of the distance between the transform & the target which will be different each time they move . so rather than that why don’t you use Vector3.MoveTowards so the shoots move always to the target with the same speed.
using UnityEngine;
using System.Collections;
public class BasicShot : RaycastController {
private Vector3 oldPosition; //The Position we had last frame
private Vector3 targetPlace; //The gameObjects Transform to chase (will be reseted every frame, so that the bullet keeps on flying to the same direction)
private int aliveSince = 0; //Counts up every frame
private float speed; //The speed this gameObject has
private int lifeSpann; //The time this gameObject will be alive for
public void SetStatsAndStart(float Speed, int LifeSpann, string thisName)
{
aliveSince = 0;
this.name = thisName; //The Name this gameObject will have. This is be needed for the GameMaster
speed = Speed;
lifeSpann = LifeSpann;
StartTheMovement();
}
//Starts the chasing of the Player
public void StartTheMovement()
{
targetPlace = GameObject.FindGameObjectWithTag("Player").transform.position;
StartCoroutine(TowardsPlayer());
}
IEnumerator TowardsPlayer()
{
while (aliveSince < lifeSpann)
{
aliveSince++;
oldPosition = transform.position;
transform.position = Vector3.MoveTowards(transform.position, targetPlace, speed * Time.deltaTime);
targetPlace = targetPlace + (transform.position - oldPosition);
yield return 0;
}
Destroy(gameObject);
}
}