Physics in Classes?

I made what I thought would be a fairly simple program is supposed to create a physics ball and draw it. The error is when it goes to draw the ellipse

Heres my main

function setup()
    game = Game()

function draw()

I create a game and run its draw

Here’s my game class

Game = class()

function Game:init()

    ball = Ball()


function Game:draw()

Then I create a ball in init and draw it in draw

Here’s my ball class

Ball = class()

function Ball:init()
    self.d = 100
    ball = physics.body(CIRCLE,self.d/2)
    ball.x = 100
    ball.y = 100
    ball.gravityScale = 1
    ball.restitution = 1
    ball.friction = 1
    print("Ball init has been ran")


function Ball:draw()

    fill(229, 16, 36, 255)
    ellipse(ball.x, ball.y, r)


And here’s where all the hard code for the ball is. The error is when it goes to draw the ellipse. In the draw for the ball it doesn’t know what ball.x and ball.y are. This code, outside of a class and just in mains setup and draw works fine so it really puzzles me why it wont work. Thanks in advance.

@Goatboy76 - you are using the name “ball” twice. You use it inside your class, but because you don’t put “self.” in front of it, it becomes a global variable, not a local one.

Then in setup you define the same name again, ball = Ball(), which overwrites the global variable containing the physics body. So there is no ball.x any more, hence the error.

The solution is to prefix ball with “self.” all the way through the ball class. Then each ball you create will have its own version of “ball” with x and y.

Ahhh I see. Thanks.