Hello,
I am trying to get a cube to move down but then go back to its starting position on mouse click using a collider but its not working. Here’s the code I have. With this code, the object moves on mouse click, hits the collider, then stops, instead of returning in the right direction. I know this code is missing the part where it returns to its original position but I can’t even have it go in the opposite direction yet. Please help me see what I’m missing! Thanks!
public class Cubes : MonoBehaviour
{
private Rigidbody cubeRb;
private Vector3 cubePosition;
// Start is called before the first frame update
void Start()
{
//cube Rigidbody
cubeRb = GetComponent<Rigidbody>();
//Where is cube at the beginning of the game
cubePosition = cubeRb.transform.position;
}
// Update is called once per frame
void Update()
{
}
private void OnMouseDown()
{
cubeRb.AddForce(Vector3.down, ForceMode.Impulse);
}
private void OnTriggerEnter(Collider other)
{
cubeRb.AddForce(Vector3.up, ForceMode.Impulse);
}
}
when the object enter the trigger, the upward force delete the downward force since they are opposite direction and same value. you should probably double the impulse force for the up position, or add a boolean that becomes true when it enters the trigger and make the object move upward in the Update function using the boolean.
If you want to move an object on a set path i’d suggest to not use forces here. That can be done but imo is more prone to errors/bugs.
Since you stated that movement does not have to be done by force, i’d suggest you try and set the position directly for example like this:
public class Cubes : MonoBehaviour
{
private Rigidbody cubeRb;
private Vector3 cubePosition;
private bool routineRunning = false;
// Start is called before the first frame update
void Start()
{
//cube Rigidbody
cubeRb = GetComponent<Rigidbody>();
}
private void OnMouseDown()
{
if(routineRunning)
return;
StartCoroutine(MovementRoutine());
}
private IEnumerator MovementRoutine()
{
float time = 0f;
while(true)
{
cubeRb.MovePosition(new Vector3(0, Mathf.Cos(time)*10f, 0));
time += Time.deltaTime;
yield return null;
}
}
}
This piece of code starts a Coroutine when you click the mouse. The routine then continuously moves the cube between starting position and (starting position - (0, 10, 0)) using a sine wave. (so it should even slow down befor turning around.
Here you can get creative how you want to do that. You could also create a public reference for a transform that you can place somewhere to define the turning point for your cube.
Let me know what you think and if that helped you.