- Home /
Incremental Move and stop
Hi guys. I've been trying to figure this one out for a few days. I've tried everything that was suggested on here and stackoverflow and quite a few other sites and nothing seems to work. I'm trying to make a cube that has different parts. That's the easy thing. The next part is the difficult part. One of these parts has to move when dragged by the player but needs to stop when the part is on the edge of the cube. I've got that to happen but it happens after the object is no longer in the vicinity of the cube.
This is the code I'm working with
private Color highlight = new Color (0, 55.0F, 0);
private float moveX;
private float moveSpeed = 1.0f;
public float minX, maxX;
//Highlight the object we are going to move
void OnMouseOver() {
renderer.material.color += highlight;
}
//Remove highlight when mouse isn't on the object
void OnMouseExit() {
renderer.material.color = Color.white;
}
// Use this for initialization
void Update()
{
float mouseX = Input.GetAxis("Mouse X");
if (mouseX < 0)
moveX = -50.0f * moveSpeed * Time.deltaTime;
else if (mouseX > 0)
moveX = 50.0f * moveSpeed * Time.deltaTime;
else moveX = 0.0f;
}
//while dragging mouse move object
void OnMouseDrag()
{
Vector3 move = new Vector3(0.0f + moveX, 0.0f, 0.0f);
transform.Translate (move * moveSpeed * Time.deltaTime);
}
void OnCollisionExit()
{
transform.Translate (0, 0, 0);
}
Thank you for any help you can provide regarding this matter.
Answer by NoseKills · Oct 08, 2014 at 03:37 PM
After transform.Translate(), cap the x-position of the transform:
if (transform.position.x > maxX)
{
Vector3 capped = transform.position;
capped.x = maxX;
transform.position = capped;
}
else if (transform.position.x < minX)
{
Vector3 capped = transform.position;
capped.x = minX;
transform.position = capped;
}
Just remember to set $$anonymous$$X and maxX to a value and not waste 3 hours of your life like me. Worst mistake I've ever made.
Your answer
![](https://koobas.hobune.stream/wayback/20220613164636im_/https://answers.unity.com/themes/thub/images/avi.jpg)