Question by
Allgames88 · Feb 14 at 10:02 AM ·
floatmultiple
I need to move multiple objects to a position multiple of 0.16. But it doesnt work.
Im Using Unity 2D.
Okay, so i need to move an object to its nearest position multiple of 0.16, to do this i started rounding its coordinates and leaving only two decimals, after that, i was checking if the position was multiple, if not, rest 0.01f to the float, and repeat, if yes, it would stop checking and move the object to that position.
The problem is that all the objects in a positive position always end in 0,0, and all the objects in a negative position, wont move at all, the bucle just never stops, but i dont get why is it failing.
By the way, im from Spain so sorry if there is something misspelled.
Here is the code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SingleGrass : MonoBehaviour
{
//Variable declarations.
public string ID;
public int level;
float Posx;
float Posy;
public float Decimaly;
public float Decimalx;
bool checkx = true;
bool checky = true;
// Start is called before the first frame update
void Start()
{
Posx = transform.position.x;
Posy = transform.position.y;
Decimalx = GetDecimal(Posx);
Decimaly = GetDecimal(Posy);
Vector2 RoundedPosition = new Vector2(GetDecimal(Posx),GetDecimal(Posy));
transform.position =RoundedPosition;
}
// Update is called once per frame
void Update()
{
//If the position that its checking its not a multiple of 0.16, it will go and check the position - 0.01.
if(Decimalx % 0.16 != 0 && checkx){
Decimalx = Decimalx - 0.01f;
Decimalx = GetDecimal(Decimalx);
}
//If the position its checking IS multiple of 0.16, it will stop checking and will give that position to the x coordinates of the object.
if(Decimalx % 0.16 == 0){
transform.position = new Vector2(Decimalx,GetDecimal(transform.position.y));
checkx = false;
}
//If the position that its checking its not a multiple of 0.16, it will go and check the position - 0.01.
if(Decimaly % 0.16 != 0 && checky){
Decimaly = Decimaly - 0.01f;
Decimaly = GetDecimal(Decimaly);
}
//If the position its checking IS multiple of 0.16, it will stop checking and will give that position to the y coordinates of the object.
Decimaly = GetDecimal(Decimaly);
if(Decimaly % 0.16 == 0){
transform.position = new Vector2(GetDecimal(transform.position.x),Decimaly);
checky = false;
}
}
/*======== Math Calculation Functions ========*/
//This function will round any float, and will only left 2 decimals.
public float GetDecimal(float b){
float TruncatedFloat = Mathf.Round(b*100.0f)*0.01f;
float a = /*Mathf.Round(b) - */TruncatedFloat;
//Debug.Log(a);
return a;
}
}
Comment