Sign up ×
Game Development Stack Exchange is a question and answer site for professional and independent game developers. It's 100% free, no registration required.

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

share|improve this question
    
Does it not work for you? Why? – Vadim Tatarnikov Aug 7 at 8:22
    
The enemy shoots at random directions up, left, right, and down, but never towards me – Borislav Aug 7 at 8:31
    
look at the edit please – Borislav Aug 7 at 8:33
    
Will it work if you don't randomize the rotation? – Vadim Tatarnikov Aug 7 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 – Borislav Aug 7 at 8:36

1 Answer 1

up vote 3 down vote accepted

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.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.