Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

add bounce effect to object with code.

Discussion in 'Physics' started by krishtetali2595, Dec 10, 2018.

  1. krishtetali2595

    krishtetali2595

    Joined:
    Nov 29, 2018
    Posts:
    7
    I have written script for moving object in horizontal direction now I want to add bounce force on collision with bouncy objects.How can I do it..? Here is the code of object for moving.. thank you

    using System.Collections;
    using UnityEngine;

    public class movement : MonoBehaviour {
    public float speed = 18;
    private Rigidbody rig;

    // Use this for initialization
    void Start () {
    rig = GetComponent<Rigidbody>();
    }

    // Update is called once per frame
    void Update () {
    float haxis = Input.GetAxis("Horizontal");
    Vector3 movement = new Vector3(haxis, 0, 0) * speed * Time.deltaTime;
    rig.MovePosition(transform.position + movement);
    }
    }
     
  2. dgoyette

    dgoyette

    Joined:
    Jul 1, 2016
    Posts:
    4,193
    First of all, your physics code should go in the FixedUpdate() method instead of the Update() method. You'll run into frame-rate dependent problems if you do physics in Update(). (https://answers.unity.com/questions/1014110/why-should-you-update-physics-in-fixedupdate.html)

    Now, do you want to make other objects bounce off this object, or make this object bounce off other things, or both? The way you have it now, other non-kinematic rigidbodies should be moved by your object, but the object itself won't be moved, since you're manually setting its position. I only use MovePosition for things that I consider to not behave realistically. For example, I use it on sliding doors that open and close, where I more or less give that door infinite force. With MovePosition, you're basically telling Unity that you're moving that object manually.

    If you want your object to move and potentially bounce off of other colliders it hits, you should probably be using AddForce instead. It's trickier to use AddForce, as it won't give you the exact control of MovePosition, but it means that it will take into account other forces acting on your object.