Hi, I tried to use this code :
public Vector2 GetPointOnUnitCircleCircumference()
{
float randomAngle = Random.Range(0f, Mathf.PI * 2f);
return new Vector2(Mathf.Sin(randomAngle), Mathf.Cos(randomAngle)).normalized;
}
that I found here, but it doesn’t work. have you some ideas?
inicosia99:
it doesn’t work
What does that mean? What result do you get instead?
Olmi
November 6, 2019, 3:37pm
3
Please use Code tags so that it’s more readable.
What does not work?
To me it looks like it works perfectly.
You need to add a position to your random result, if you want to spawn enemies around your player. (Just as an example, I don’t know what you are trying to do.)
Here’s an example:
Vector3 spawnPoint = playerPosition + GetPointOnUnitCircleCircumference();
GameObject.Instantiate(gameObjectToBeInstanced, spawnPoint, Quaternion.identity);
(In my example it’s 3D position, so you have to maybe adapt it.)
it spawn the obstacles really near the player, I don’t know how to add a radius.
Olmi:
Please use Code tags so that it’s more readable.
What does not work?
To me it looks like it works perfectly.
You need to add a position to your random result, if you want to spawn enemies around your player. (Just as an example, I don’t know what you are trying to do.)
Here’s an example:
Vector3 spawnPoint = playerPosition + GetPointOnUnitCircleCircumference();
GameObject.Instantiate(gameObjectToBeInstanced, spawnPoint, Quaternion.identity);
(In my example it’s 3D position, so you have to maybe adapt it.)
How can I add the radius, cause it spawn really near the player
Olmi
November 7, 2019, 10:43am
6
If the radius position you randomize is unit length, which it is, just multiply it:
Vector2 spawnPoint = playerPosition + GetPointOnUnitCircleCircumference() * spawnDistance;
And in the situation your vector is not length of 1, you can normalize it.
spawnDistance would be a float value you expose to the Inspector UI by making it public or use SerializeField attribute in front of the field name:
// Public
public float spawnRadius;
// private, but forced to be serialized by Unity
[SerializeField] float spawnRadius;
So, just multiply the value with 5 (for example) and your objects will spawn 5 units away from your player.
It might be a good idea to search for vector math basics as you will stumble to similar issues soon. Here are a few links that you might find useful:
https://docs.unity3d.com/Manual/UnderstandingVectorArithmetic.html
https://wildbunny.co.uk/vector-maths-a-primer-for-games-programmers/
https://gamedevelopertips.com/vector-in-game-development/
It is the first thing I did but it didn’t work…