2075 / Unity / 2D / Відштовхування
Платформа або монстр між стінами Потребує Rigidbody2D float x = 0.1f; void FixedUpdate() { transform.Translate(new Vector3(x, 0f, 0f)); } void OnTriggerEnter2D(Collider2D other) { x = -x; }
З відштовхуванням один від одного Rigidbody2D rb; Vector3 lastVelosity; void Start() { rb = GetComponent<Rigidbody2D>(); rb.AddForce(new Vector2(200f, 200f)); } void FixedUpdate() { lastVelosity = rb.velocity; } private void OnCollisionEnter2D(Collision2D coll) { rb.velocity = Vector3.Reflect(lastVelosity, coll.contacts[0].normal); }
Вічний рух
private void OnCollisionEnter2D(Collision2D coll) { var speed = lastVelosity.magnitude; var direction = Vector3.Reflect(lastVelosity.normalized, coll.contacts[0].normal); rb.velocity = direction * Mathf.Max(speed, 1f); // 1 - min speed }