Problem MoveBall (Pong 2D)

Hello, I have a problem, i wrote the Script C# of the ball when it’s moving ecc.

but there’s a problem: Assets/BallControl.cs(56,67): error CS1061: Type UnityEngine.Collider2D' does not contain a definition for rb’ and no extension method rb' of type UnityEngine.Collider2D’ could be found (are you missing a using directive or an assembly reference?)

I don’t know what’s does mean, because in all the code it’s all right except for the last part, here’s all the code:

using UnityEngine;
using System.Collections;

public class BallControl : MonoBehaviour {

//dichiarole classi
public float trhust;
public Rigidbody2D rb;
public Vector2 velocity;

//Usethisfor initialization
void Start () {
hi (2.0f);
GoBall ();
}

IEnumerator hi (float secs) {
yield return new WaitForSeconds (secs);
}

void GoBall(){
float rand = Random.Range (0.0f, 100.0f);
if (rand < 50.0f) {
rb.AddForce (new Vector2 (20.0f, 15.0f));
} else {
rb.AddForce (new Vector2 (-20.0f, -15.0f));
}

}

void hasWon() {
var vel = rb.velocity;
vel.y = 0;
vel.x = 0;
rb.velocity = vel;

gameObject.transform.position = new Vector2 (0, 0);
}

void resetBall() {
var vel = rb.velocity;
vel.y = 0;
vel.x = 0;
rb.velocity = vel;

gameObject.transform.position = new Vector2 (0, 0);

hi (0.5f);
GoBall ();
}

void OnCollisionEnter2D (Collision2D coll) {
if (coll.collider.CompareTag (“Player”)) {
var velY = rb.velocity;
velY.y = (velY.y / 2.0f) + (coll.collider.rb.velocity.y / 3.0f);
rb.velocity = velY;
}

}
}

Firstly, please use code tags when posting code on the forums so we can read your code more easily.

The error comes from this line:

velY.y = (velY.y / 2.0f) + (coll.collider.rb.velocity.y / 3.0f);

rb is a variable defined by this script to reference the rigidbody that is attached to this script’s GameObject. You can’t use the variable name rb to refer to some other object, unless it’s a different script with its own rb member.

Instead, just use this:

velY.y = (velY.y / 2.0f) + (coll.rigidbody.velocity.y / 3.0f);

coll, which is an object of type Collision2D, has a rigidbody variable that’s used to directly access the other object’s Rigidbody in a collision.

1 Like

Thank you :smile:

1 Like