Hello. I’m coding a top-down shooter (more specifically I’m expanding the Space Shooter tutorial) and I’m trying to make a bullet that is pointed to the player’s position at the time of shooting. My problem is that I can instantiate the bullet but I cannot get it to move towards the player. It doesn’t even point towards him. This is my code:
using UnityEngine;
using System.Collections;
// Este script es provisional (12-7-2015 22:56)
public class BasicEnemyController : MonoBehaviour {
public float speed;
public float alienHp;
public float bulletSpeed;
public GameObject bullet;
float fireTimer;
Vector3 target;
GameObject player;
Transform targetTransform;
float nextFire;
void Start ()
{
fireTimer = 0.0f;
GetComponent<Rigidbody> ().velocity = transform.forward * speed;
}
void Update ()
{
fireTimer -= 1;
if (fireTimer <= 0.0f)
{
Attack ();
}
}
void Attack ()
{
float step = bulletSpeed * Time.deltaTime;
player = GameObject.FindGameObjectWithTag ("Player");
target = new Vector3 (player.GetComponent<Rigidbody>().position.x, player.GetComponent<Rigidbody>().position.y, player.GetComponent<Rigidbody>().position.z);
var rotate = Quaternion.LookRotation(player.transform.position - transform.position);
transform.rotation = Quaternion.Slerp(transform.rotation, rotate, step);
transform.Translate (0, 0, step);
fireTimer = 180;
Instantiate(bullet, transform.position, transform.rotation);
bullet.GetComponent<Rigidbody>().velocity = transform.forward * bulletSpeed;
}
}
I know the code is a bit messy, I’ve been hacking through it all the day trying to get it working. Sorry for the inconvenience.