- Home /
How do I Round with Vector3.up
I have a character that moves on 32x32 tiles and when it moves, I use Vector.up in the inspector I get values like 0.1599999 instead of 0.16 how can I fix this? Here is my code:
void Update () {
buttonCooldown--;
if (canMove) {
pos = transform.position;
move ();
}
if (moving) {
if (transform.position == pos) {
moving = false;
canMove = true;
move ();
}
transform.position = Vector3.MoveTowards (transform.position, pos, Time.deltaTime * speed);
}
}
private void move () {
if (buttonCooldown <= 0){
if (Input.GetAxisRaw("Vertical") >= 1){
if (dir != DIRECTIONG.UP) {
anim.Play("Stand Up", -1, 0f);
buttonCooldown = 10;
dir = DIRECTIONG.UP;
} else {
canMove = false;
moving= true;
pos +=Vector3.up * 0.32f;
}
Answer by toddisarockstar · Apr 09, 2017 at 07:09 PM
What is the problem? are you having problems when compairing?
Vector3 rv = new Vector3 (0.1599999f, 0.1599999f, 0.1599999f);
rv = new Vector3 (Mathf.Round(rv.x * 100), Mathf.Round (rv.y * 100), Mathf.Round (rv.z * 100))*0.01f;
// this shows (0.16,0.16,0.16) in the inspector
Answer by NoseKills · Apr 09, 2017 at 02:45 PM
Short answer: You can't. You have to live with it. Floating point numbers have limited precision.
You are not really saying what kind of a problem this floating point precision "error" causes for you. The number you are seeing is practically 0.16 and 99% of the time this kind of errors don't cause any problems visually for example.
If it causes other kinds of logic problems, you just have to program around them.
For example if an object is supposed to be positioned on a grid with 0.5 unit wide cells, rather store the object's grid cell coordinates as integers, use these integers for game rules and position checking, and use transform.position (vector3 of floats) only for positioning the visual representation (gameObject) on screen - dont try to use transform.position for checking if an object is at coordinates (1,1) == (0.5f, 0.5f) because sooner or later some object will be at .49999... or at .5000...1.
Here's a pretty good video about why this is happening in general
Answer by Cuttlas-U · Apr 09, 2017 at 04:51 PM
hi; I usually write an "if" statement to check the difference between the value and the final value and make it correct my self when the function is at the end ;
Your answer
Follow this Question
Related Questions
How to smooth movement object in one-axis? 1 Answer
Npc Movement 0 Answers
using MoveObject to perform 2 translations at the same time 1 Answer