# Unity 3D - Rotate towards object with random offsets

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:

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:

but never towards me, or backwards

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

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.