Search Unity

Release button for a moving cube.

Discussion in 'Scripting' started by manishsaini74, Jun 13, 2018.

  1. manishsaini74

    manishsaini74

    Joined:
    Jun 3, 2018
    Posts:
    1
    Hi,

    I have a cube which is moving on x and z axis i want to make a release button by which cube will stop moving and fall down to ground using gravity.

    My code for movement is :

    using UnityEngine;
    using System.Collections;

    public class BlockMover : MonoBehaviour
    {


    // define the possible states through an enumeration
    public enum motionDirections { Spin, Horizontal, Vertical };

    // store the state
    public motionDirections motionState = motionDirections.Horizontal;

    // motion parameters
    public float spinSpeed = 180.0f;
    public float motionMagnitude = 0.05f;


    // Update is called once per frame
    private void Update()
    {

    // do the appropriate motion based on the motionState
    switch (motionState)
    {
    case motionDirections.Spin:
    // rotate around the up axix of the gameObject
    gameObject.transform.Rotate(Vector3.up * spinSpeed * Time.deltaTime);
    break;

    case motionDirections.Vertical:
    // move up and down over time
    gameObject.transform.Translate(Vector3.up * Mathf.Cos(Time.timeSinceLevelLoad) * motionMagnitude);
    break;

    case motionDirections.Horizontal:
    // move up and down over time
    gameObject.transform.Translate(Vector3.right * Mathf.Cos(Time.timeSinceLevelLoad) * motionMagnitude);
    break;
    }

    }
    }
     
  2. Doug_B

    Doug_B

    Joined:
    Jun 4, 2017
    Posts:
    1,596
    You just need to add and use a rigid body. You will want to look into use of the isKinematic flag. If you are unfamiliar with them, just click "Learn" at the top of this page and you will find some good tutorials there.

    P.s. please use code tags for pasting code. :)