Unity implements desktop bounce sample code

Time:2021-12-30

1: Demo video

2: Code implementation


using UnityEngine;
 
public class Ball : MonoBehaviour
{
    private Rigidbody rigid;
 
    private Vector3 lastDir;
 
    public float speed = 30;
 
    private void Awake()
    {
        rigid = GetComponent<Rigidbody>();
 
        rigid.velocity = new Vector3(1, 0, 1) * speed;
    }
 
    private void LateUpdate()
    {
        lastDir = rigid.velocity;
    }
 
    private void OnCollisionEnter(Collision other)
    {
        if (other.gameObject.tag == "Wall")
        {
            Vector3 reflexAngle = Vector3.Reflect(lastDir, other.contacts[0].normal);
            rigid.velocity = reflexAngle.normalized * lastDir.magnitude;
        }
    }
}

You can also add

Create physical materials

After modifying the value, rebound collision can occur

This is the end of this article about the sample code of unity to realize desktop rebound. For more information about unity rebound, please search the previous articles of developeppaer or continue to browse the relevant articles below. I hope you will support developeppaer in the future!