- Home /
help with making enemy projectile fly at player at one speed
I've got a script for the projectile which makes it fly in the players direction when it is instantiated, it works most of the time but sometimes if I'm close to the enemy the projectiles either moves really slowly or freezes in place completely, I'm not sure if it has something to do with the .normalized or not.
public class bulletatplayer : MonoBehaviour
{
float moveSpeed = 20f;
float curTime = 1;
float nextDamage = 1;
Rigidbody rb;
CharacterController target;
Vector3 moveDirection;
[SerializeField]
bool bSpawnOther = false;
[SerializeField]
GameObject goSpawn;
// Start is called before the first frame update
void Start()
{
rb = GetComponent<Rigidbody>();
target = GameObject.FindObjectOfType<CharacterController>();
moveDirection = (target.transform.position - transform.position).normalized * moveSpeed;
rb.velocity = new Vector3(moveDirection.x, moveDirection.y, moveDirection.z);
}
// Update is called once per frame
void Update()
{
}
void OnCollisionEnter(Collision collision)
{
if (collision.gameObject.tag != "enemy")
{
Destroy(this.gameObject);
if (bSpawnOther)
Instantiate(goSpawn, transform.position, Quaternion.identity);
}
if (collision.gameObject.name == "Player")
{
if (curTime <= 0)
{
HPscript.hpValue -= 1;
Debug.Log("Collided with + " + collision.gameObject.name);
curTime = nextDamage;
}
else
{
curTime -= Time.deltaTime;
}
HPscript.hpValue -= 1;
Debug.Log("Collided with + " + collision.gameObject.name);
}
}
}
thanks for any help.
At first glance it looks like it should be working, moveDirection = (target.transform.position - transform.position).normalized * moveSpeed;
is correctly calculating the direction vector and multiplying with a speed factor and the next line could be reduced to rb.velocity = moveDirection;
.
It should be something wrong with the way it's handling the collision. Are you getting the issue when the projectile reaches player?
Thanks for commenting, you made me see what the problem might be. The issue had something to do with the if (collision.gameObject.tag != "enemy") part of the script, when the projectile touched an enemy it would just stop moving, I don't know why this is but I think I've got it to work at least now by taking that part out of the script.
Could be Destroy(this.gameObject);
. I haven't understood what you want to do exactly, but this seems bad practise destroying the object then having more code afterwards using it's transform etc. Try moving the whole if statement to the end of the function and the Destroy itself on the end of the if statement.
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Move projectile in a specific direction 0 Answers
Distribute terrain in zones 3 Answers