Am I organizing and instancing the objects in a bad way? I've also included my new function for the rock module.
The shared variable issue became apperent when I tried this.
Code: Select all
local rock1 = Rock:new(nil, player.pos)
print(rock1.pos.y)
local rock2 = Rock:new(nil, player.pos)
print(rock1.pos.y)
print(rock2.pos.y)
Code: Select all
--------------- enemy rock module ---------------
-- inherits from entity
local entity = require "entity"
local asset = require "accessAssest"
Rock = Entity:new()
math.randomseed(69) -- nice
function Rock:new(rock, playerPos)
rock = Entity:new(rock, xNew, yNew, angle, img)
setmetatable(rock, self)
self.__index = self
self.ID = "Rock"
self.pos = {}
self.pos.x, self.pos.y = Rock:spawnRockPosition()
self.angle = Rock:getAngleToPlayer(playerPos)
-- velocity of entity in x,y
self.maxVel = 10
self.accelRate = 10
self.vel = {x = 0, y = 0}
-- velcoity of the entity's rotation
self.rotVel = 0
self.maxRotVel = math.pi
self.accelRotRate = math.pi*2
self.rotationDir = 0
-- changable later
self.img = asset.getAssest("rockIMG")
-- initilize hitbox information, a rectangle at the center of the rock
self.hitx = self.pos.x - self.img:getWidth()/4
self.hity = self.pos.y - self.img:getHeight()/4
self.hitWidth = self.img:getWidth()/2
self.hitHeight = self.img:getHeight()/2
return rock
end
Code: Select all
function Entity:new(entity, xNew, yNew, angle, img)
entity = entity or {}
setmetatable(entity, self)
self.__index = self
--[[
IMPORTANT NOTE:
Variables that children classes depend on need to be redefined in the
new of the child class. Otherwise, it the child class uses
the variables from the entity class. These variables are used here for the
definition of the entity class functions.
]]
-- position of entity in x,y
self.pos = {x = 0, y = 0}
-- velocity of entity in x,y
self.maxVel = 300
self.accelRate = 200
self.vel = {x = 0, y = 0}
-- velcoity of the entity's rotation
self.rotVel = 0
self.maxRotVel = math.pi
self.accelRotRate = math.pi*2
-- set initial positions of entity
self.pos.x = xNew or 0
self.pos.y = yNew or 0
-- EDIT INPUT OF NEW: is either nil or the img paramater, can be reset useing setImg method
self.img = nil
-- starting angle of entity
self.angle = angle or math.pi
-- draw angle
-- insert the new entity into the entity table
table.insert(entityTable, self)
-- increment the stored number of entities
entityNumber = entityNumber + 1
return entity
end