Answer the question
In order to leave comments, you need to log in
How to create a piston in Unity like in Minecraft?
I created a 3D model.
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.
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);
}
}
}
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question