- Home /
Setting transform.position not behaving properly
Im begining in Unity, so I might be missing something, but i have 4 game objects: 2 players in each side of the screen, and 2 virus on the midlle. The players can shoot boubles to move the virus away from them. To do that i have this code in each virus:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class greenVirus : MonoBehaviour
{
[SerializeField] Transform otherVirus;
Vector3 horizontal_move = new Vector3(1.4f, 0);
Vector3 vertical_move = new Vector3(0, 3);
private void OnTriggerEnter2D(Collider2D collision)
{
if (collision.gameObject.name == "blueBouble(Clone)"
&& transform.position.x < 5.6f
&& otherVirus.position != transform.position + horizontal_move)
{
transform.position += horizontal_move;
Destroy(collision.gameObject);
}
else if (collision.gameObject.name == "redBouble(Clone)"
&& transform.position.x > -5.6f
&& otherVirus.position != transform.position - horizontal_move)
{
transform.position += -horizontal_move;
Destroy(collision.gameObject);
}
else
{
Destroy(collision.gameObject);
}
}
}
The viruses shoul move ins steps of 1.4 units, to a maximum of 5.6/-5.6. But when i try to run this, everyting goes fine except for when i try to "centralize" the virus again with the boubles (making the x value 0). In the game view and the scene view I can clearly see the the virus is in the correct place, but in the inspector the x position shows as -2.384186e-07, which is really strange. I have other function to move the virus around, but they seem to be working properly, the only probem i find is here.
Hope someone can help me, and thenks in advance :)
Answer by Bunny83 · Jan 24, 2021 at 06:42 PM
Never use equal / unequal conditions like this:
otherVirus.position != transform.position + horizontal_move
when you deal with floating point numbers. Those will most likely never be satisfied. Always use either ranges or greater / lower than limits.
Answer by N-8-D-e-v · Jan 24, 2021 at 06:56 PM
Adding on to @Bunny83 's answer, otherVirus position could be something like 4.99999999999 and transform.position could be 5. Instead do something like this
if (Vector3.Distance(otherVirus.position, transform.position) < rangeVariable)
I already knew about that but if i have for example 1.5, and I add 0.1, then subtract 0.1 shouldn't it still be 1.5? And what do you mean by range variable? The distance between the 2 transforms? And if that is that suposed to solve my problem, why does it work "visualy" in the scene and game views, but is only wrong in the inspector and scripts? And, one more question, what does -2.384186e-07 even mean?
Sory for too many questions hahaha. Thanks :)
the range variable is just a sort of "forgiveness" between the two variables. 4.99999 is not equal to 5, but they are super close. You would probably set this variable to something low like 0.1. In-2.384186e-07, e is just a way to display super large numbers :)