Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Question How do I Stop Pong Ball Gravitating Towards Paddle?

Discussion in 'Scripting' started by DevIggy, Jul 22, 2023.

  1. DevIggy

    DevIggy

    Joined:
    Feb 21, 2022
    Posts:
    3
    Hello. I'm creating a Pong game in Unity to practice my skills as a beginner game dev, and have run into an issue where the ball gravitates toward a single paddle, and once it bounces off said paddle, it will simply gravitate back to that paddle.

    Here is an example to demonstrate what I mean:


    How can I fix this so that it doesn't gravitate towards any paddle at all?
    Screenshot 2023-07-22 163853.png Screenshot 2023-07-22 164034.png
     
  2. venediklee

    venediklee

    Joined:
    Jul 24, 2017
    Posts:
    143
    Logic bug:

    you never change the speed parameter to the move the ball to the other side. Consider multiplying the speed’s X by -1 when the ball hits the platform

    PS: please use code snippets next time instead of sharing a screen shot
     
    DevIggy, Ryiah and Chubzdoomer like this.
  3. zulo3d

    zulo3d

    Joined:
    Feb 18, 2023
    Posts:
    510
    You can remove the FixedUpdate. The ball doesn't need a force constantly being added to it.

    Add an OnCollisionEnter event to the bats so that when the ball collides with the bat it can be given a push with AddForce()


    Code (CSharp):
    1.  
    2. using UnityEngine;
    3.  
    4. public class PushIt : MonoBehaviour
    5. {
    6.     public Vector3 pushForce;
    7.  
    8.  
    9.     void OnCollisionEnter(Collision collision)
    10.     {
    11.         collision.gameObject.GetComponent<Rigidbody>().AddForce(pushForce);
    12.     }
    13. }
     
    DevIggy likes this.
  4. zulo3d

    zulo3d

    Joined:
    Feb 18, 2023
    Posts:
    510
    Oh and you'll need the walls to also push the ball when it hits them!. :)
     
  5. DevIggy

    DevIggy

    Joined:
    Feb 21, 2022
    Posts:
    3
    Thank you, this solved the problem. :)
     
  6. DevIggy

    DevIggy

    Joined:
    Feb 21, 2022
    Posts:
    3
    Thanks for your answer!

    P.S. sorry, I will use code snippets next time
     
    Yoreki and venediklee like this.
  7. orionsyndrome

    orionsyndrome

    Joined:
    May 4, 2014
    Posts:
    3,043
    I actually like the effect! :) Too bad it's undesirable :)
     
    zulo3d likes this.