This question was
closed Feb 10, 2018 at 07:34 PM by
unity_S0ZCLiVP1XXH-w for the following reason:
The question is answered, right answer was accepted
Question by
unity_S0ZCLiVP1XXH-w · Feb 10, 2018 at 07:08 PM ·
c#movementtransform.positionmathf.clamplimited
Need help with limited movement with mathf clamp
I make the game on android. I need to make an object that would move along the x and y axes limitedly. I tried several options - it did not work out. First: the standard unity tutorial about what I need. But when game is starting my object moves to 0.6 in y and z axes, in x moves correctly. I don't know why. This is script:
[System.Serializable]
public class Boundary
{
public float xMin, xMax, yMin, yMax;
}
public class TargetMoving : MonoBehaviour
{
public float speed;
public Boundary boundary;
Rigidbody rb;
void Start()
{
rb = GetComponent<Rigidbody>();
}
void FixedUpdate()
{
float moveHorizontal = Input.GetAxis("Horizontal");
float moveVertical = Input.GetAxis("Vertical");
Vector3 movement = new Vector3(moveHorizontal, moveVertical, 0.0f);
rb.velocity = movement * speed;
rb.position = new Vector3
(
Mathf.Clamp(rb.position.x, boundary.xMin, boundary.xMax),
0.0f,
Mathf.Clamp(rb.position.y, boundary.yMin, boundary.yMax)
);
}
}
Second: I created this script myself. And here when game is starting my object moves to strange position - right and down, and don't control correctly. Script:
public class TargetMoving : MonoBehaviour
{
public float minX;
public float maxX;
public float minY;
public float maxY;
public float speedX = 100.0f;
public float speedY = 100.0f;
float positionY;
float positionX;
void Update()
{
if (Time.time > 1.0)
if (Input.GetMouseButton(0))
{
positionX += CnInputManager.GetAxis("Mouse X") * speedX * Time.deltaTime;
positionY -= CnInputManager.GetAxis("Mouse Y") * speedY * Time.deltaTime;
positionY = Mathf.Clamp(positionY, minY, maxY);
positionX = Mathf.Clamp(positionX, minX, maxX);
transform.position = new Vector3(positionY, positionX, 0);
}
}
}
I need a help. I need simple limited moving. Sorry for my English.
Comment
Answer by yummy81 · Feb 10, 2018 at 07:28 PM
In your first script, line 30, replace this code:
rb.position = new Vector3
(
Mathf.Clamp(rb.position.x, boundary.xMin, boundary.xMax),
0.0f,
Mathf.Clamp(rb.position.y, boundary.yMin, boundary.yMax)
);
with this:
rb.position = new Vector3
(
Mathf.Clamp(rb.position.x, boundary.xMin, boundary.xMax),
Mathf.Clamp(rb.position.y, boundary.yMin, boundary.yMax),
0.0f
);