Love2D Renderer Error - debugging

I am following a tutorial that is teaching me about how to make a platformer. In the second tutorial, we started to make a renderer. Whenever I run the code and test the renderer, I get this error
Error: main.lua:24: attempt to index global 'renderer' (a nil value)
I have no idea how to fix it, so here is my code.
renderer.lua
local Renderer = {}
local num_of_layers = 5
local insert = table.insert
local remove = table.remove
function Renderer:create()
local renderer = {}
--
renderer.drawers = {}
for i = 0,num_of_layers do
renderer.drawers[i] = {}
end
--
function renderer:addRenderer(obj, Layer)
local l = layer or 0
insert(self.drawers[l], obj)
end
--
function renderer:draw()
for layer = 0,#self.drawers do
for draw = 0,#self.drawers[layer] do
local obj = self.drawers[layer][draw]
if obj ~= nil then
obj:draw()
end
end
end
end
return renderer
end
--
return Renderer
Here is main.lua
local Renderer = require("libs/renderer")
Renderer = Renderer:create()
function love.load()
love.graphics.setBackgroundColor(255, 255, 255)
--Loading Classes
player_load()
--Loading Classes
end
--
function love.update(dt)
end
--
function love.draw()
renderer:draw()
end
Thanks to everyone who is reading!

Lua is case sensitive.
Renderer = Renderer:create() is not the same as
renderer = Renderer:create()

Related

How to update colors of an image pixels in julia?

Objective: to change color intensity of pixels
Code:
using Images, ImageView;
function updateColors(path::String)
if isfile(path)
img = load(path);
chnlView = channelview(img);
chnlView[chnlView .> 0.7] = 0.9;
imshow(img);
else
info("Error: Image Not Found!");
end
end
#By Prof.Bogumił Kamiński
function quit()
print("Press q to quit!");
while true
opt = getChar();
if opt == 'q'
break
else
continue
end
end
end
#By Prof.Bogumił Kamiński
function getChar()
ret = ccall(:jl_tty_set_mode, Int32, (Ptr{Cvoid},Int32), stdin.handle, true)
ret == 0 || error("unable to switch to raw mode")
c = read(stdin, Char)
ccall(:jl_tty_set_mode, Int32, (Ptr{Cvoid},Int32), stdin.handle, false)
c
end
updateColors("/opt/julia/pictures/test.jpg");
quit();
Error:
no method matching setindexshape(::Float64, ::Int64)
Please help me in resolving the issue!
You should broadcast the assignment operation like this:
chnlView[chnlView .> 0.7] .= 0.9

XNA Gamestudio - NPCs get stuck at walls and each other (Visual Basic)

I created NPCs that move that direction you're standing at the moment. If they touch something, they never will move again. I don't have a clue and already wasted like 6 hours searching the fault.
That is my Move-Method:
Overrides Sub Move()
Dim actorPosition As Vector2
Dim spieler As Actor
For Each obj As Actor In Actor.ActorList
If TypeOf obj Is Actor And obj.Alive And obj.ObjektTyp = "A"c Then
actorPosition = obj.position
spieler = obj
End If
Next
Dim difPos As Vector2 = position - actorPosition
normaldifpos = difPos
normaldifpos.Normalize()
If lastTimeAttack + intervallBetweenAttack1 < Game1.Game1Time Then
If difPos.Length < range Then
Select Case ObjektTyp
Case "Z"c
spieler.leben -= stärke
Case "H"c
For Each obj As Objekt In ObjList
If TypeOf obj Is Spells Then
If obj.ObjektTyp = "Z"c And obj.Alive = False Then
obj.position = position
obj.richtung = -normaldifpos
obj.senderE = Me
obj.stärke = stärke
obj.Alive = True
Exit For
End If
End If
Next
End Select
lastTimeAttack = Game1.Game1Time
End If
End If
If difPos.Length() < agroRange Then
If spieler IsNot Nothing And Not collide((normaldifpos + New Vector2(-4, -4) * speed)) Then
position = position - normaldifpos * speed
Else
End If
End If
End Sub
And this my collide method:
Public Overridable Function collide(vek As Vector2) As Boolean
Dim extrahitbox As Rectangle
extrahitbox = Hitbox
extrahitbox.X += vek.X
extrahitbox.Y += vek.Y
For Each obj As Objekt In Objekt.ObjList
If TypeOf obj Is Spells Or TypeOf obj Is Key Or TypeOf obj Is PowerUP Or TypeOf obj Is Coin Then
Else
If extrahitbox.Intersects(obj.Hitbox) Then
Return True
End If
End If
Next
For Each Act As Actor In Actor.ActorList
If Act IsNot Me Then
If extrahitbox.Intersects(Act.Hitbox) Then
Return True
Else
End If
End If
Next
If extrahitbox.X < 0 Then
Return True
ElseIf extrahitbox.Right > 1280 Then
Return True
ElseIf extrahitbox.Top < 0 Then
Return True
ElseIf extrahitbox.Bottom > 720 Then
Return True
End If
End Function
I would appreciate help!
From your example it looks object stuck because once when it collide with other object you are not doing any update to position. After determing collision you have to calculate how deep object is inside other object and move it back to previous position.
One way is after you determinate collision you simply negate velocity.
object.Position -= object.Velocity
object.Velocity = new vector2(0,0)
Other way is more accurate as velocity remain same and if your origin is on top-left position. It collision happened, it will position your object right next to other object depend from where collision happened.
If obj.Intersect(otherObj) Then
Dim newPos as new vector2d = obj.Position
if (obj.velocity.x>0) then newPos.x = otherObj.Left - obj.width
if (obj.velocity.x<0) then newPos.x = otherObj.right
obj.Position = newPos
End If
So basicly goes like this
put position to temp varialbe
check collision
if collision happened set original to temp
draw

handle events in corona lua

Iam new to corona, so I dont know how to organize my code to best. I am trying to regiser click when user click on leftHam image, but I dont how to do it most efficently. Right now I am getting leftHam is nil although on creation it should be assinged a value.
local composer = require( "composer" )
local widget = require( "widget" )
local scene = composer.newScene()
local _H = display.contentHeight
local _W = display.contentWidth
leftNavBtn = nil
local navbarGroup
function scene:create( event )
local sceneGroup = self.view
local background = display.newImage("res/bg.png" )
background:scale( _W, _H )
background.x = _W
background.y = _H
local navbarGroup = display.newContainer(_W, _H/4)
navbarGroup.x = _W /2
--navbarGroup.y = 0
local top_bar = display.newImage("res/home/top_bar.png")
top_bar.y = top_bar.height/2
navbarGroup:insert(top_bar)
--local leftNavBtn = display.newImageRect("res/home/hamburger.png", 100, 100)
leftNavBtn.y = leftNavBtn.height/1.5
leftNavBtn.x = - navbarGroup.width/2 + leftNavBtn.width
leftNavBtn = display.newImageRect("res/home/hamburger.png", 100, 100)
leftNavBtn.y = leftNavBtn.height/1.5
leftNavBtn.x = - navbarGroup.width/2 + leftNavBtn.width
navbarGroup:insert(leftNavBtn)
local rightNavBtn = display.newImageRect("res/home/hamburger.png", 100, 100)
rightNavBtn.y = leftNavBtn.height/1.5
rightNavBtn.x = navbarGroup.width/2 - leftNavBtn.width
navbarGroup:insert(rightNavBtn)
end
function test()
print("clickedddddddddddd")
end
function leftNavBtn:touch(event)
if event.phase == "began" then
display.getCurrentStage( ):setFocus(self)
self.isFocus = true
elseif self.isFocus then
if event.phase == "moved" then
print("moved")
elseif event.phase == "ended" or event.phase == "cancelled" then
display.getCurrentStage( ):setFocus(nil)
self.isFocus = false
end
end
return true
end
leftNavBtn:addEventListener( "touch", test )
scene:addEventListener( "create", scene )
return scene
Do you mean leftNavBtn because leftHam doesn't exist anywhere.
You are creating leftNavBtn in scene:create but are attempting to use it before calling that function anywhere (the leftNavBtn:addEventListener( "touch", test )) line.
Within scene:create you also use leftNavBtn before creating it because you commented out this line local leftNavBtn = display.newImageRect("res/home/hamburger.png", 100, 100) without commenting out the two lines after it (which set of three lines you then duplicate immediately after that).

Scrolling and dragging in Corona --> BUG?

I have a event listener assigned to an object. This then triggers the startDrag function. I'm moving my character in the game with dragging. But as soon as I scroll or move the display, my dragging function gets all messed up. It doesn't react as it should and the object(event.target) can't be controlled at all.
Did anyone else had this experience?
Is this a corona bug?
How can I solve this?
Can I temporarily disable the startDrag event listener for the time of scrolling? Or maybe restart it?
All help would be greatly appreciated.
Here is the code...
local physics = require( "physics" )
physics.start()
physics.setContinuous( false )
display.setStatusBar( display.HiddenStatusBar )
physics.setScale( 60 )
physics.setDrawMode( "hybrid" )
local height = display.contentHeight
local width = display.contentWidth
local allElements = display.newGroup()
local texsGroup = display.newGroup()
local backGround = display.newRect(0,0-height,width,2*height)
backGround:setFillColor(91,91,91)
backGround:toBack()
local wallBottom = display.newRect(texsGroup, 0,height-20,width,20)
physics.addBody(wallBottom, "static", { density=5, friction=0.5, bounce=0.3 } )
local tex = {}
local numberRips = 60
local texSize = {
-- w: texwidth, h: texheight, s: strength required
{w=30, h=20, s=1},
{w=20, h=10, s=1.5},
{w=10, h=10, s=2},
}
local r
local lim = display.newGroup()
local function createRips()
local originX = 0
local originY = height -75
for i=0,numberRips do
r = math.random(3)
local x = originX + math.random(width)
local y = originY - math.random(2*height)
tex[i] = display.newRect(lim, x, y, texSize[r].w, texSize[r].h)
tex[i].status = "active"
tex[i].size = texSize[r].s
if (r == 1) then
tex[i]:setFillColor(51,255,0)
elseif (r == 2) then
tex[i]:setFillColor(255,51,51)
elseif (r == 3) then
tex[i]:setFillColor(51,51,255)
end
end
end
createRips()
local w, h, r = width/2, height - 265, 12
local L = display.newCircle(w-115,h+29,r)
local buttonRadius = 35
local button3 = display.newCircle((L.x),(L.y),buttonRadius)
button3.myName = "L"
allElements:insert(button3)
allElements:insert(lim)
allElements:insert(L)
local d, f, b = 15, 1, 0.15
physics.addBody(L, "dynamic", { density=d, friction=f, bounce=b, radius=r } )
button3.isVisible = false
button3.isHitTestable = true
physics.addBody( button3, "static", { density=1, radius=buttonRadius } )
local function addFrictionJoint(a, b, posX, posY, lowerAngle, upperAngle, mT)
local j = physics.newJoint ( "pivot", a, b, posX, posY, rFrom, rTo)
j.isLimitEnabled = true
j:setRotationLimits (lowerAngle, upperAngle)
return j
end
-- JOINTS
addFrictionJoint( button3, L, L.x, L.y, 0, 0 )
local function startDrag( event, params )
local body = event.target
local phase = event.phase
local stage = display.getCurrentStage()
local direction = event.direction
if "began" == phase then
stage:setFocus( body, event.id )
body.isFocus = true
event.target.bodyType = "dynamic"
-- Create a temporary touch joint and store it in the object for later reference
if params and params.center then
-- drag the body from its center point
body.tempJoint = physics.newJoint( "touch", body, body.x, body.y )
else
-- drag the body from the point where it was touched
body.tempJoint = physics.newJoint( "touch", body, event.x, event.y )
end
--body.tempJoint.maxForce = 0.25*body.tempJoint.maxForce
-- Apply optional joint parameters
if params then
local maxForce, frequency, dampingRatio
if params.maxForce then
-- Internal default is (1000 * mass), so set this fairly high if setting manually
body.tempJoint.maxForce = params.maxForce
end
if params.frequency then
-- This is the response speed of the elastic joint: higher numbers = less lag/bounce
body.tempJoint.frequency = params.frequency
end
if params.dampingRatio then
-- Possible values: 0 (no damping) to 1.0 (critical damping)
body.tempJoint.dampingRatio = params.dampingRatio
end
end
elseif body.isFocus then
if "moved" == phase then
-- Update the joint to track the touch
body.tempJoint:setTarget( event.x, event.y )
elseif "ended" == phase or "cancelled" == phase then
stage:setFocus( body, nil )
body.isFocus = false
-- Remove the joint when the touch ends
body.tempJoint:removeSelf()
body.bodyType = "static"
end
end
-- Stop further propagation of touch event
return true
end
function moveCamera(e)
if button3.y < -lim.y + 300 then
allElements.y = -(button3.y - 300)
end
end
Runtime:addEventListener("enterFrame", moveCamera)
button3:addEventListener( "touch", startDrag )
When you scroll the screen the touch event and the physics object are in different coordinate systems. See localToContent/globalToContent

Reapeat/until help in lua

Hello I've been trying to get this code to work, I even cheated and added in the goal to my code and its still not accepting my answer, any suggestions?
-- Functions...
function p() -- For user imput..
print("Enter # and try to get the closest to it! (Valid range is 1-100)")
local var = tonumber(io.read())
if var == nil then
var = 0
end
return var
end
--Start main code..
-- Initialize the pseudo random number generator (I'm on windows...)
math.randomseed( os.time() )
math.random(); math.random(); math.random()
-- Setting goal
goal = math.random(1,100)
-- Guessing loop...
repeat
g = p()
print(g)
print(goal)
until g == Goal
print("YOU GUESSED THE GOAL!")
Replace the G by a lower case g.
until g == goal

Resources