- Home /
How are vector3s instantiated?
I can't find any relevant information specifically detailing the default parameters of a new'd up vector3.
public class MyObject
{
var vec = new Vector3();
}
I'm gonna assume that a new vector3's default is (0,0,0), but I can't find an answer or doc specifically stating that.
public class MyObject
{
var vec = new Vector3(Random.Range(-1.0f, 1f),
Random.Range(-1.0f, 1f),
Random.Range(-1.0f, 1f));
}
If that's the case, and an update method is called on this vector, does that mean it will select vector positions from a range of -1,1 RELATIVE to 0,0,0?
The goal is to create a vector relative to a specific position that on update selects random points relative to that position.
Answer by Aviryx · Aug 27, 2020 at 01:58 AM
https://docs.unity3d.com/ScriptReference/Vector3.Index_operator.html
public Vector3 p;
void Start()
{
Debug.Log(p[0]);
Debug.Log(p[1]);
Debug.Log(p[2]);
}
Shows it to be 0, 0, 0
There doesn't appear to be any actual documentation that specifically states it though.
That makes sense, a little dumb i didn't think to just check each individual vector but yaknow.
Answer by N-8-D-e-v · Aug 27, 2020 at 12:54 AM
A Vector3's default values are indeed, (0, 0, 0). If I understand you correctly, you already have a vector, and you want to create a new one based on the old one with Random.Range. If so, you could pretty easily just do this
Vector3 pos = //the vector you start with
float range = //range of points
Vector3 newPos = pos;
pos.x += Random.Range(-range, range);
pos.y += Random.Range(-range, range);
pos.z += Random.Range(-range, range);
I'm sure there is a better way to do this, but this is very simple and just off the top of my head. Also it is best practice not to use var, but to implicitly state the variable type (in your case Vector3). If you have more questions or my answer wasn't clear/didn't work for you the let me know, and I will try to help.
I think that's what I'm trying to do, it's a typical camera shake function.
Vector3 cameraPos = GetComponent().position;
Vector3 randomPos = new Vector3(Random.Range(cameraPos.x -1, cameraPos.x +1), (cameraPos.y -1, cameraPos.y +1), cameraPos.z);
cameraPos = randomPos;
Does that make sense? Initially, i had it as
Vector3 randomPos = new Vector3(Random.Range(-1, 1), (-1, 1), cameraPos.z);
and the random position would initialize at 0,0,0, and pick random ranges +/- 1 relative to 0,0,0, and then return to the initial camera position.
if your camera position is at (0, 0, 0) then the way you had it initially is fine, otherwise, the method I showed you takes into account the offset of your camera
Your answer
Follow this Question
Related Questions
Using Vector3 in ViewportToWOrldPoint 1 Answer
Random position of an object spawned from a spawn point? 0 Answers
Random.Range Vector3 2 Answers
Random spawn script not working correctly 3 Answers
Random.Range(..) not working 1 Answer