I’m working on a game mechanic where to objects move with the player with one being normal, and the other being the opposite. I have the normal part functioning fine, but when I tried to do the opposite in code it’s giving me this weird error as my object flies off the screen.
“transform.position assign attempt for “Blue Box” is not valid. Input position is {-Infinity, -28888778970870709809, 454534534534534534543}”
Any idea what is going wrong? Is my opposite movement code wrong?
if (moving)
{
if (isRed)
{
targetPosition = player.transform.position + startPosition; // Red Box (Normal) **These two lines work fine**
transform.position += (targetPosition - transform.position);
}
else
{
targetPosition = player.transform.position + startPosition; // Blue Box (Opposite) ** These two lines send object flying off screen with error **
transform.position += (targetPosition + transform.position);
}
}
else
{
startPosition = transform.position - player.transform.position; // Resting
transform.position = player.transform.position + startPosition;
}
}
The problem is you’re trying to set a direction vector targetPosition - transform.position as a position vector.
Vectors in Unity can represent several things. They can be a position point in 3D space, and they can be a direction pointing to a specific direction from some position in 3D space.
When you + or - two position vectors you’ll get a direction vector. targetPosition + transform.position returns direction from targetPosition to transform.position. targetPosition - transform.position returns direction from transform.position to targetPosition.
So, in your code for isRed Unity is trying to set cube position to its current position and then move it in the direction from its current position to target position. It seems like it works as intended, but it’s not actually. Make cube’s original position farther from the target and you’ll see the cube jittering between these two positions.
In second part for !isRed you place the cube on the position and set a direction which points ‘from’ the target, so the cube is going away from the scene.
To make it work, you need to determine a distance which you want your cubes to be from the target and use something like this:
float distance = 1f;
if (moving)
{
if (isRed)
{
// posiition for a cube which is going to be in 1 unit in front of player
// player's position plus a direction vector forward from player multiplied by a distance
targetPosition = player.transform.position + player.transform.forward * distance;
transform.position = targetPosition;
}
else
{
// the same for another cube but a direction should be back from player
targetPosition = player.transform.position + player.transform.back * distance;
// or if there's no back vector
// targetPosition = player.transform.position + player.transform.forward * -distance;
// or another way
// targetPosition = player.transform.position - player.transform.forward * distance;
transform.position = targetPosition;
}
}