Hello! I wanted to make basic visual effect of incoming bullets (of course slower than bullets from machine gun in real world ) coming from bad cubes to player.
Here is my “try code” - moving and shooting part:
public float minDistance = 3;
public float maxDistance = 15;
void Update () {
float distance = Vector3.Distance(myCharacter.position, player.position);
if (distance <= maxDistance && distance >= minDistance) {
transform.LookAt (player);
myCharacter.rotation = Quaternion.Slerp (myCharacter.rotation, Quaternion.LookRotation (player.position - myCharacter.position), rotationSpeed * Time.deltaTime);
transform.Translate (moveSpeed * Vector3.forward * Time.deltaTime);
}
if (distance <= 20 && distance >= 7 ) {
Shoot ();
}
}
public int count = 1;
public float forceValue = 1200;
public Rigidbody bulletPref;
Transform bulletPos;
void Shoot(){
int freq = 90;
if (count % freq == 0) {
transform.LookAt(player);
Rigidbody bullet = Instantiate (bulletPref, myCharacter.position, myCharacter.rotation) as Rigidbody;
bullet.rigidbody.AddForce (myCharacter.forward* forceValue );
}
count++;
}
}
But it is working only sometimes. At other time bullet is going in different direction (180 degrees wrong). What can I do? I must use Raycast?
Thx for any advice or working example.