I
I
Ilya Valferov2021-01-07 19:16:44
Unity
Ilya Valferov, 2021-01-07 19:16:44

How to create a piston in Unity like in Minecraft?

I created a 3D model. 5ff7344300419658621520.jpeg
It is necessary that the piston moves forward at the click of the mouse, pushes the object in front and returns to its original position. 5ff73139c1af9404232097.jpeg

I originally used transform.position for the slide out element, but it just jumps to coordinates and returns the same way.
I tried it with MoveTorwards , but strange things happen there. Everything moves smoothly in one direction, and the object shakes in the opposite direction

public class Porshen3D : MonoBehaviour
{
   public GameObject midleShtyka;
   public Vector3 toPosition;
   public Vector3 firstPosition;
   public float force;
    bool click;
   
  
    void Start()
    {
        toPosition = midleShtyka.transform.position + toPosition;
        firstPosition = midleShtyka.transform.position;
    }

    void FixedUpdate()
    {
     if ( click)
        {
            
            StartCoroutine(MoveForward());
        }

    }
    private void OnMouseDown()
    {    
        click = true;
    }
    IEnumerator MoveForward()
    {
        if (click)
        { 
            midleShtyka.transform.position = Vector3.MoveTowards(midleShtyka.transform.position, toPosition, Time.deltaTime * force);
            yield return new WaitForSeconds(1);
            midleShtyka.transform.position = Vector3.MoveTowards(toPosition, firstPosition, Time.deltaTime * force);
           
        }


    }

}


At the moment, I just made a regular animation that is called through a trigger in the code on a mouse click on an object. Is it right? Isn't it a crutch? s
How to do it right?
If there is any book or resource after which all questions disappear, I will be very grateful)))

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question