1
\$\begingroup\$

I am making a pong game and here's the problem. The ball hits the enemy paddle and instead of reflecting the ball just takes the paddle with it.

Ball Brains -

using UnityEngine;

public class BallBrains: MonoBehaviour
{
    private int seedX, seedY;
    private Rigidbody2D rb;

    void Start ()
    {
        Random.InitState (69);

        seedX = Random.Range (0, 1);
        seedY = Random.Range (0, 1);

        rb = GetComponent<Rigidbody2D>();
    }

    void FixedUpdate ()
    {
        if (seedX == 0)
        {
            rb.AddForce (new Vector2 (0.5f, 0f) );
        }
        else if (seedX == 1)
        {
            rb.AddForce (new Vector2 (-0.5f, 0f) );
        }

        if (seedY == 0)
        {
            rb.AddForce (new Vector2 (0f, 0.5f) );
        }
        else if (seedY == 1)
        {
            rb.AddForce (new Vector2 (0f, -0.5f) );
        }
    }

    void OnCollisionEnter ()
    {

    }
}

Enemy Movement -

using UnityEngine;

public class EnemyMovement : MonoBehaviour
{
    private BallBrains ball;
    private Rigidbody2D rb;

    void Start ()
    {
        ball = FindObjectOfType<BallBrains>();
        rb = GetComponent<Rigidbody2D>();
    }

    void FixedUpdate ()
    {
        if (ball.transform.position.y > transform.position.y)
        {
            rb.AddForce(new Vector2(0f, 10f));
        }

        if (ball.transform.position.y < transform.position.y)
        {
            rb.AddForce(new Vector2(0f, -10f));
        }
    }
}

**Player Movement - **

using UnityEngine;

public class PlayerMovement : MonoBehaviour
{
    private Rigidbody2D rb;

    private bool verticalMovementUp = false;
    private bool verticalMovementDown = false;

    void Start ()
    {
        rb = GetComponent<Rigidbody2D>();
    }


    void Update ()
    {
        verticalMovementUp = Input.GetKey(KeyCode.W);
        verticalMovementDown = Input.GetKey(KeyCode.S);
    }

    void FixedUpdate ()
    {
        if (verticalMovementUp) {
            rb.AddForce(new Vector2(0f, 10f));
        }

        if (verticalMovementDown) {
            rb.AddForce(new Vector2(0f, -10f));
        }
    }
}

ballenemy paddleerror

Also, quick question - How do I set random seed for the direction the ball moves in at the start?

\$\endgroup\$
1
  • 1
    \$\begingroup\$ Please ask one question per post. Is it safe to assume you investigated making the paddles kinematic? \$\endgroup\$
    – DMGregory
    Sep 4 '21 at 19:15
1
\$\begingroup\$

For your first question, make your Rigidbody2D Kinematic for ignoring the forces acting on the paddle.

For your second question,

How do I set random seed for the direction the ball moves in at the start?

  Vector3 randomDirection = new Vector3(Random.Range(0,360),Random.Range(0, 360),transform.position.z);
  transform.rotation = Quaternion.Euler(randomDirection);
\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .