- Home /
Assigning R,G,B values to X,Y,Z to change colour in accordance with changing position
I'm looking for a way to assign red to X axis, green to Y axis and blue to Z axis. This is so I can move an object through the unity environment (say in a 5x5x5 space) and it will change colour accordingly.
So if it was in a random position of (1,3,1) then its colour would be (80,150,80) causing the object to turn a green shade. - **these values are just random to be used as an example, not how i expect it to work
This is assuming colours go from 0-255 values.
So on the X axis, from positions 1 to 5 the colour would change from red 0 to 255 (or however unity decides on colour)
I have very little experience with Unity.
Thanks
Answer by Chronos-L · Apr 14, 2018 at 08:23 AM
well... you already have the core concept, just put them together.
Transform _t;
Material _m;
void Awake()
{
_t = GetComponent<Transform>();
_m = GetComponent<MeshRenderer>().material;
}
void Update()
{
Vector3 pos = _t.position; // Getting position of your gameobject
//pos /= 5 * 255; ///(since you are mapping 0...5 to 0...255) Incorrect
pos /= 5;
_m.color = new Color(pos.x, pos.y, pos.z);
}
"Color" is in the range 0 - 1, not 0 - 255. So just do
Vector3 pos = _t.position / 5;
_m.color = new Color(pos.x, pos.y, pos.z);
This of course assumes a worldspace range of 0 - 5 in each axis. The easiest, inspector adjustable solution would be to use an empty gameobject in the scene. It's origin would define the starting corner (equal to black) and (1,1,1) in local space would be the opposite corner (equal to white). You can scale the object to whatever size you like (5,5,5) in your example.
Transform space; // our empty gameobject
Vector3 pos = space.InverseTransformPoint(_t.position);
_m.color = new Color(pos.x, pos.y, pos.z);
This way you can move, rotate and scale your "space" however you like.
ps: this line:
pos /= 5 * 255;
doesn't even map 0-5 to 0-255 but maps the space 0-1275 to 0-1. x/=y
is a short hand for: x=x/(y)
. So your line would be
pos = pos / (5 * 255);
Apologies, that was very sloppy of me. Thanks for the correction.