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. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

2d pong game

Discussion in 'Scripting' started by CodeWurm, Dec 19, 2015.

  1. CodeWurm

    CodeWurm

    Joined:
    Nov 8, 2014
    Posts:
    316
    Hello I'm trying to create a pong game with two players, and I would like to know what code I can attach to my ball object to create a collision and bounce effect.

    Ball.script
    if (gameObject.name == "player" || player1)
    {
    What do I need to put in here???
    }

    Second question
    When I start my game, the balls stays at the same position, what can I do to make the ball move to a direction so the two players can start playing or if I tab a button that the ball starts to move to a direction.
     
  2. buckius82

    buckius82

    Joined:
    Nov 19, 2013
    Posts:
    40
    If your ball has a rigid body use the players monobehavior colider functions to apply forces to the ball
    On collider enter for example

    Second using a class on the ball ints awake () function have it choose a direction and apply force to its own rigidbody in that direction
     
  3. tedthebug

    tedthebug

    Joined:
    May 6, 2015
    Posts:
    2,570
    If you are using physics you can put a physics material onto the ball & set bounce to maximum so it reacts of the paddles correctly, for the initial bounce set a random direction as stated above, you can even put it at a random angle so it isn't always going straight left or right at the start.

    Also, if player1 is the name of the other player you probably need inverted comma's around it as well in your if statement.
     
  4. CodeWurm

    CodeWurm

    Joined:
    Nov 8, 2014
    Posts:
    316
    And if iam just using a self made sprite ball, what code can i use??
     
  5. buckius82

    buckius82

    Joined:
    Nov 19, 2013
    Posts:
    40
    You can add rigidbody and coliders to sprites use the 2d version