2
\$\begingroup\$

Title is a little confusing, but let me explain:

I want to make the enemies look at the player, and shoot at him, with random precision, meaning that one time the enemy will shoot a little bit to the left of the player, next time a little bit to the right of him, and sometimes exactly at him.

Currently I have this scene: enter image description here

The turret rotates, and when the green direction spots the player, it shoots a bullet facing the player (the green arrow).

Now I need where the rotation is passed for the Instantiate, to have some random precision, and I don't know how to do it. Here's what I have so far

Vector3 pos = new Vector3(firingPoint.transform.position.x, firingPoint.transform.position.y, firingPoint.transform.position.z);

float playerX = playerObject.transform.position.x;
float playerY = playerObject.transform.position.y;
float playerZ = playerObject.transform.position.z;

float randomX = Random.Range(playerX - 1f, playerX + 1f);
float randomY = Random.Range(playerY - 1f, playerY + 1f);
float randomZ = Random.Range(playerZ - 1f, playerZ + 1f);    

Quaternion aimPrecision = Quaternion.LookRotation(new Vector3(randomX, randomY , randomZ));

Instantiate(bulletPrefab, pos, aimPrecision);

How can I do this?

EDIT: Right now, the enemy shoots like this: enter image description here

but never towards me, or backwards

\$\endgroup\$
5
  • \$\begingroup\$ Does it not work for you? Why? \$\endgroup\$
    – John Smith
    Commented Aug 7, 2015 at 8:22
  • \$\begingroup\$ The enemy shoots at random directions up, left, right, and down, but never towards me \$\endgroup\$
    – Borislav
    Commented Aug 7, 2015 at 8:31
  • \$\begingroup\$ look at the edit please \$\endgroup\$
    – Borislav
    Commented Aug 7, 2015 at 8:33
  • \$\begingroup\$ Will it work if you don't randomize the rotation? \$\endgroup\$
    – John Smith
    Commented Aug 7, 2015 at 8:35
  • \$\begingroup\$ if I pass in the default values of playerObject (x, y and z) the enemy shoots only to the left, or only up \$\endgroup\$
    – Borislav
    Commented Aug 7, 2015 at 8:36

1 Answer 1

3
\$\begingroup\$

I found the solution myself. Here's what I've done:

I took the default forward rotation of the firingPoint object, and split it into it's parts - x, y, z, w.

Then from these floats, I create a new Quaternion using the constructor method:

float randomX = Random.Range(-0.1f, 0.1f);
float randomY = Random.Range(-0.1f, 0.1f);
float randomZ = Random.Range(-0.1f, 0.1f);
float randomW = Random.Range(-0.1f, 0.1f);

Quaternion oldRot = firingPoint.rotation;
Quaternion newRot = new Quaternion(oldRot.x + randomX, oldRot.y + randomY, oldRot.z + randomZ, oldRot.w + randomW);

Then every time this code get's called, the object will be instantiated with random rotation facing the player.

\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .