0
\$\begingroup\$

I've just started looking into developing with Unity, and read through the tutorials and introductions. For my first project, I decided to try something simple - so a breakout clone. However, when the ball hits the player, the player gets knocked down a few pixels.

The player and ball have BoxCollider2D attached to them, and the player also has a RigidBody2D attached to it. The player is also checked as a "static" object. The ball moves towards the player using transform.translate().

Here is the balls script:

using UnityEngine;
using System.Collections;

public class BallScript : MonoBehaviour {


    public float speed;
    // Use this for initialization
    void Start () {

    }

    // Update is called once per frame
    void Update () {
        this.transform.Translate (Vector3.down * speed * Time.deltaTime);
    }

    void OnCollisionEnter2D (Collision2D col) {
        this.speed = -speed;
    }

}
\$\endgroup\$
1
  • \$\begingroup\$ After toying around a bit, it appears that I do not fully understand rigidbody2D - as if I make the ball also have a rigidbody2D component, there is no knockback effect. \$\endgroup\$ Commented Mar 5, 2015 at 23:57

1 Answer 1

3
\$\begingroup\$

What you want to do for this kind of game, is not directly change the transform of the ball but change the velocity of the rigidbody.

Set friction to 0 in the rigidbody of the ball and lock the movements of the panels.

Have a script that detects if the ball collides with the panel, on collision delete the panel and let the physics response do the work.

Set the physics material of the ball/walls/panels to an elastic collision.

If you want to add some speed when the ball hits a panel/player, increment/alter the velocity or apply a force to the rigidbody.

The player should not be static. Static is used to optimize non moving GameObjects. The player should have a its rigidbody x and y positions locked and moved with a script on user input. Lock the rigidbody under constraints in the inspector.

Hope this helps!

Here is a Tutorial that might help!

\$\endgroup\$

You must log in to answer this question.

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