skip to Main Content

I’m writing a game for unity and I encountered a problem, I need the ball to bounce off the walls all the time without losing speed, my ball crashes into the wall and stays in it, here is the code

I tried to solve this problem through gpt chat and articles and YouTube videos on YouTube`

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Enemy : MonoBehaviour
{
    public float speed = 10f;

    private Rigidbody rb;
    private Vector3 lastVelocity;
    private Vector3 goalVelocity;


    void FixedUpdate()
    {
        lastVelocity = rb.velocity;
        rb.velocity = goalVelocity;
    }

    void OnCollisionEnter(Collision collision)
    {
        if (collision.gameObject.CompareTag("Wall"))
        {
            Vector3 reflection = Vector3.Reflect(lastVelocity, collision.contacts[0].normal);
            rb.velocity = reflection.normalized * speed;
        }
    }

    void Start()
    {
        rb = GetComponent<Rigidbody>();
        if (rb == null)
        {
            Debug.LogError("Rigidbody component not found!");
            return;
        }
        goalVelocity = rb.velocity;
        Vector3 randomDirection = new Vector3(Random.Range(-1f, 1f), 0f, Random.Range(-1f, 1f)).normalized;
        rb.AddForce(randomDirection * speed, ForceMode.VelocityChange);
    }
}

2

Answers


  1. I think you could skip the normalization and just do this:

    void OnCollisionEnter(Collision collision)
    {
        if (collision.gameObject.CompareTag("Wall"))
        {
            Vector3 reflection = Vector3.Reflect(lastVelocity, collision.contacts[0].normal);
            rb.velocity = reflection;
        }
    }
    

    This will probably fix the issue because I think you set speed to zero (it’s not declared in your code).

    You could also just give the wall a physics material with bounce set to 1. That would be easier than all that code, though it would make anything else bounce off the wall too.

    EDIT: The reason you can skip the normalization part is because normalizing a vector means dividing it by its magnitude, and your speed is the magnitute of your velocity. You’re dividing it by a number and then multiplying it by that same number again (or at least attempting to, if speed really is zero).

    Login or Signup to reply.
  2. This can be done through physics materials as well.

    Create a Physic material in project. Then just simply add that to any physics component (Rigidbody, or Collider).

    On Physics material you can see the friction. Which can make it ideal.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search