Nil
Nil

Reputation: 39

Generating GameObject in front of player infinitely

enter image description hereI have a 'player' 3D Object and a 'circle' 3D Object. The player can move towards the circles one by one already.

I need the circles to generate randomly in front of the player when spacebar is pressed, e.g spacebar pressed then one circle generated, spacebar pressed again then another circle generated and so on.

As in randomly generated, it needs to spawn on the radius of the existing circle, e.g 2 units away from the circle anywhere in front that is not behind (180 degree)

All this text may make the question seem complicated but all I really need is another circle created in front of the existing one.

It would also be helpful if you could use some sort of random rotation of the player in order to generate in front of the player.

This is my code so far, feel free to completely wipe my original code in the answer:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class CreateObject : MonoBehaviour
{

    public Vector3 playerPos;
    public GameObject yourObject;

    // Use this for initialization
    void Start()
    {
        playerPos = playerPos.transform.position;
        Instantiate(yourObject, new Vector3(playerPos.transform.position.x +  5, playerPos.transform.position.y, playerPos.transform.position.z), Quaternion.identity);
    }

    // Update is called once per frame
    void Update()
    {
    }
}

Thanks in advance!

Upvotes: 0

Views: 242

Answers (1)

Milad Qasemi
Milad Qasemi

Reputation: 3059

you can rotate your player around your Up Vector between your max and min angle then use your distance and direction to find the new position
for the random angle part you can generate a random number with
RandomAngle=Random.Range(MinAngle,MaxAngle);
then use it with
Quaternion.AngleAxis(RandomAngle, playerUpVector)
to rotate it around your players Upvector, I dont know what you used for your Up vector but normally it is Vector3.up
then multiply it by your players direction(playerLocalDirection) that which normally is Vector3.forward

Vector3 newPos= myPos + Quaternion.AngleAxis(RandomAngle, playerUpVector) * playerLocalDirection * DistanceFromPlayer;

Upvotes: 1

Related Questions