- Home /
Rounding transform.position? With parents
How do I round my object(a buildable), to the nearest say .25, .5 or 1(does not matter which), in position(x,y,z), and the rotation to the nearest 30 degrees, I know this could be achieved with Mathf.Round() but how do I make it that it does not mess up the local position/rotation. It is a buildable which is a gameobject that in in a fp controller("Main Camera/Tools/TheObject" to be exact). It also has a move up/down command, which also I need help making it work with the global position.
So I guess the main question is how do I make the global position/rotation round, without messing up the local position/rotation.
I guess another way to word this is: The local position is 0,0,0 and the global is not known, the local rotation is -90,0,0 and global is not known, how would I round the global without messing up the local, and still having the object infront a play, but with a rounded transform.
Code(if needed):
using UnityEngine;
using System.Collections;
public class Buildable : MonoBehaviour {
public PlayerItemManager itemManager;
private float holdTimer = 0;
public float objectYPosOffset = 0;
void Start(){
itemManager = transform.root.GetComponent<PlayerItemManager> ();
objectYPosOffset = -2.3f;
}
void OnEnable(){
itemManager = transform.root.GetComponent<PlayerItemManager> ();
objectYPosOffset = -2.3f;
}
void Update(){
ManageInput ();
RoundObjectTransform ();
ManageBuilding ();
}
private void ManageInput(){
if (Input.GetKeyUp (KeyCode.PageUp)) {
objectYPosOffset += 0.25f;
}
if (Input.GetKeyUp (KeyCode.PageDown)) {
objectYPosOffset -= 0.25f;
}
}
private void ManageBuilding(){
if (Input.GetMouseButton (1)) {
holdTimer+=Time.deltaTime;
if(holdTimer > 1){
holdTimer = 0;
RoundObjectTransform();
PlaceObject();
}
}
}
private void RoundObjectTransform(){
Vector3 pos = transform.localPosition;
pos.y = 1 + objectYPosOffset;
transform.localPosition = pos;
Vector3 rot = transform.eulerAngles;
rot.x = -90;
transform.eulerAngles = rot;
//transform.rotation.x = -90;
}
private void PlaceObject(){
GameObject go = Resources.Load ("Buildables/"+gameObject.name) as GameObject;
GameObject obj = Network.Instantiate (go,transform.position,transform.rotation,0) as GameObject;
itemManager.UseCurrentSlot (true);
}
}
Look if u change the global position of an object then its local position will change for sure. If you want the local position not to change then keep this object in an empty gameobject and change the empty gameobject's global position. In this way your object's localposition will be intact.