Cannot translate an object before collision is resolved - lua

When I compile this is showing
error: Cannot translate an object before collision is resolved
and when I'm building app for android it shows me an error#5 (null).
Here's my code:
function onLocalCollision(meteor, event)
if event.phase == "began" then
if event.object1.myName == "meteor" and
event.object2.myName == "rocket" then
score = score - 1
scoreNumber.text = score
restart.isVisible = true
meteor.x = 500
meteor.y = 300
meteor2.x = 500
meteor2.y = 200
meteor3.x = 500
meteor3.y = 100
event.object2.alpha = 0.2
rocket:applyForce(-150,0,rocket.x,rocket.y)
lives = lives -1
livesNumber.text = lives
if lives < 1 then
lives = 3
score = 0
scoreNumber.isVisible = false
livesText.isVisible = false
livesNumber.isVisible=false
hearticon.isVisible = false
scoreText.isVisible = false
gameover.isVisible = true
restart.x = 100000
end
end
end
end
meteor.collision = onLocalCollision
Runtime:addEventListener("collision", meteor)

The problem with your code is that you cannot translate during a collision (function) so if you just say:timer.performWithDelay(100, function() rocket:applyForce(-150,0,rocket.x,rocket.y) end, 1) it should resolve your problem and/or just create a callback function.
"Modifying Objects
The objects involved in the collision should not be removed or any of it's properties altered during a collision event. You should use timer.performWithDelay() if they want to modify object position values or other properties within the collision events.
Removing the object or modifying the properties in the collision event could cause the simulator to crash."
http://docs.coronalabs.com/api/event/collision/index.html

Related

Roblox: how to script VectorForce

I'm very new (2 days) to Roblox and Lua, so don't bite me too hard please.. =)
What I am trying to do is to script VectorForce for the Part I've also instanced from code.
In simulation Attachment and VectorForce did create, but without any expected effect.
Please, look at my script and tell me where do I need to dig.
local sandblock = script.Parent
local sandblock_health = 5
local function blockJump(object)
local jump_att = Instance.new("Attachment", object)
local jump_force = Instance.new("VectorForce", object)
jump_force.ApplyAtCenterOfMass = true
jump_force.Attachment0 = jump_att
jump_force.RelativeTo = Enum.ActuatorRelativeTo.World
jump_force.Force = Vector3.new(10,1000,-10)
jump_force.Enabled = true
-- here: what is the difference between Enabled and Active?
--jump_force.Active = true
end
local function onTouch(object)
--print("К блоку прикоснулся "..object.Name)
if object.Name == "Handle" then
sandblock_health = sandblock_health - 1
print(sandblock_health)
if sandblock_health < 1 then
local sandblock_drop1 = Instance.new("Part", workspace)
sandblock_drop1.Size = Vector3.new(2,2,2)
sandblock_drop1.Position = sandblock.Position + Vector3.new(0,5,-1)
blockJump(sandblock_drop1)
sandblock_drop1.Material = "Metal"
sandblock_drop1.BrickColor = BrickColor.new("Gold")
sandblock_drop1.Name = "Gold"
print("Вы добыли "..sandblock_drop1.Name)
sandblock:Destroy()
end
end
end
sandblock.Touched:Connect(onTouch)
Solved it.
The product of workspace's gravity and part's mass is much higher than 1000 in my Force vector.
Code below works as expected:
jump_force.Force = Vector3.new(10, game.Workspace.Gravity * object.Mass * 1.35, -10)
jump_force.Enabled = true
wait(0.4)
jump_force.Enabled = false
It seems like the issue is that when you made the onTouch function, you had a parameter: object. However when you called the function on a player touching the part, you put no parameter: sandblock.Touched:Connect(onTouch). To fix this, do: sandblock.Touched:Connect(onTouch(<object_parameter>))

Displaying a random object chosen from a table

I'm trying to create a function that would choose one of four objects from a table that would then create it. Essentially what's meant to happen is if objects 1-3 are chosen they would be considered "regular" and the "player" would have to catch them while the fourth object is "special" and would take points away if caught.
here's the table
local objects = {
"object1",
"object2",
"object3",
"object4"
}
this is the code I'm using in place of what I want currently (mostly to make sure everything else in my code is working)
local function spawnObject()
object = display.newImage("images/object1.png")
object.x = math.random(screenLeft+ 30, screenRight-30)
object.y = screenTop-100
object.width = 100
object.height = 100
object.Number = 1
object.type = "regular"
object.score = 5
object.rotation = math.random(-20,20)
physics.addBody(object, "dynamic", {density =1, friction =1, bounce = .5})
end
Start with this...
local function spawnObject()
local objects = {
"object1",
"object2",
"object3",
"object4"
}
object = display.newImage("images/"..objects[math.random(3)]..".png")
object.x = math.random(screenLeft+ 30, screenRight-30)
object.y = screenTop-100
object.width = 100
object.height = 100
object.Number = 1
object.type = "regular"
object.score = 5
object.rotation = math.random(-20,20)
physics.addBody(object, "dynamic", {density =1, friction =1, bounce = .5})
end
...for choosing 1-3.
If you dont like math.random(3) you can do a table.remove(objects,1) 3 times so it is clear the 4th time is the special one.
But then have to be objects global ( outside function and not local ).
...you have to check for.

Attempt to index nil with "Touched"?

Here's the deal, I'm incorporating a teleportation system with a tool on Roblox Studio. However, this error has got me stumped. I will provide the code and other useful sources below and describe the issue after.
local tool = script.Parent.Parent
local debounce = false
local afterTeleport = false
local plrName = game.Players.LocalPlayer.Name
local char = workspace:FindFirstChild(plrName)
tool.Activated:connect(function(m)
if debounce == false then
local hum = game.Players.LocalPlayer.Character.Humanoid
local anim_feet = hum:LoadAnimation(script.Parent.Animation)
local current = anim_feet
local bodyVelocity = tool.Handle.LocalScript.BodyVelocity:Clone()
debounce = true
current:Play()
wait(1.1)
local gui = script.Parent.TransitionGui:Clone()
-- Properties for UI
gui.Parent = game.Players.LocalPlayer.PlayerGui
-- Transition
gui.Frame.BackgroundTransparency = 1
wait(0.02)
gui.Frame.BackgroundTransparency = 0.8
wait(0.02)
gui.Frame.BackgroundTransparency = 0.6
wait(0.02)
gui.Frame.BackgroundTransparency = 0.4
wait(0.02)
gui.Frame.BackgroundTransparency = 0.2
wait(0.02)
gui.Frame.BackgroundTransparency = 0
-- Teleport Player Into Sky Above Them
hum.Parent.HumanoidRootPart.CFrame =
CFrame.new(Vector3.new(hum.Parent.HumanoidRootPart.CFrame.X, hum.Parent.HumanoidRootPart.CFrame.Y + 700, hum.Parent.HumanoidRootPart.CFrame.Z))
bodyVelocity.Parent = hum.Parent.HumanoidRootPart
afterTeleport = true
wait(0.02)
gui.Frame.BackgroundTransparency = 0.2
wait(0.02)
gui.Frame.BackgroundTransparency = 0.4
wait(0.02)
gui.Frame.BackgroundTransparency = 0.6
wait(0.02)
gui.Frame.BackgroundTransparency = 0.8
wait(0.02)
gui.Frame.BackgroundTransparency = 1
wait(0.02)
end
end)
char.Touched:Connect(function(interact)
local hum = game.Players.LocalPlayer.Character.Humanoid
if afterTeleport == true then
if interact:IsA("Terrain") then
if hum.Parent.HumanoidRootPart:FindFirstChild("BodyVelocity") then
hum.Parent.HumanoidRootPart.BodyVelocity:Destroy()
end
elseif interact:IsA("Part") then
if hum.Parent.HumanoidRootPart:FindFirstChild("BodyVelocity") then
hum.Parent.HumanoidRootPart.BodyVelocity:Destroy()
end
elseif interact:IsA("MeshPart") then
if hum.Parent.HumanoidRootPart:FindFirstChild("BodyVelocity") then
hum.Parent.HumanoidRootPart.BodyVelocity:Destroy()
end
end
end
end)
To me, this seems correct. But the issue is whenever I play-test the code, the output displays an error that I don't understand. The output error is:
16:35:59.453 Players.BigBetterBuilder.Backpack.Sky Port.Handle.LocalScript:58: attempt to index nil with 'Touched' 
My goal for this tool is that when it is activated, it will teleport you into the sky 700 studs above the players' current position. It will add a BodyVelocity to the player's HumanoidRootPart causing the player to slow down the decent speed, and when the player touched the ground. It should remove the BodyVelocity allowing the player to roam around without having weird gravity.
But the function that's supposed to detect when a player touches the ground isn't working. And I, unfortunately, can't seem to solve the problem.
You've got a timing issue in your code. At the top of your script, you are trying to access the player's character model, but when this script runs, that character might not have been loaded into the workspace yet. So, when you call char.Touched:Connect(...) it throws an error because char is null.
But you've got a different problem as well. The player's character is a Model, and Model's don't have a Touched event like Parts do. So in order to use the Touched event, you either need to attach it to platforms that a character might touch, or to the Parts inside the character model.
So try moving the char.Touched connection inside a callback that fires once the player and character have properly loaded into the game, and attach the Touched connection instead to the different Parts in the character model :
local player = game.Players.LocalPlayer
player.CharacterAdded:Connect(function(character)
-- create a helper function for checking if we're touching the ground
local function checkTouchedGround(interact)
if not afterTeleport then
return
end
local shouldRemoveVelocity = false
if interact:IsA("Terrain") then
shouldRemoveVelocity = true
elseif interact:IsA("Part") then
shouldRemoveVelocity = true
elseif interact:IsA("MeshPart") then
shouldRemoveVelocity = true
end
if shouldRemoveVelocity then
local bv = character.HumanoidRootPart:FindFirstChild("BodyVelocity", 0.1)
if bv then
bv:Destroy()
end
end
end
-- listen for any time any player parts touch the ground
for _, child in ipairs(character:GetDescendants()) do
if child:isA("BasePart") then
child.Touched:Connect(checkTouchedGround)
end
end
end)

Jumping on moving platforms

I've just started using Corona SDK, and I'm having some problems applying physics on moving platforms.
Basically I have a platforms moving right to left, and when a object lands on the platform there is no friction, the object fails to move with the platform, so once the platform has moved from underneath the object, the object falls to the bottom of the screen. Has anybody else had this problem? I guess maybe a physics object loses some of its attributes but i don't know which one.
I want that the object can move with the platform, same direction and velocity.
Here's a code sample:
.....
elements = display.newGroup()
elements.anchorChildren = true
elements.anchorX = 0
elements.anchorY = 1
elements.x = 0
elements.y = 0
screenGroup:insert(elements)
player = display.newImageRect("player.png",30,50)
player.anchorX = 50
player.anchorY = 50
player.x = 80
player.y = display.viewableContentHeight - 80
physics.addBody(player, "static", {density=.1, bounce=0.1, friction=1.0})
player:setLinearVelocity( 100, -600 )
screenGroup:insert(player)
.....
....
local gameStarted = false
function jumptoplatform(event)
if event.phase == "began" then
if gameStarted == false then
player.bodyType = "dynamic"
addplatformsTimer = timer.performWithDelay(1000, addplatforms, -1)
moveplatformsTimer = timer.performWithDelay(2, moveplatforms, -1)
gameStarted = true
player:setLinearVelocity( 100, -600 )
else
player:setLinearVelocity( 100, -600 )
end
end
end
function moveplatforms()
for a = elements.numChildren,1,-1 do
if(elements[a].x > -150) then
elements[a].x = elements[a].x - 6
else
elements:remove(elements[a])
end
end
end
function addplatforms()
platform1 = display.newImageRect("platform.png",200,80)
platform1.anchorX = 0
platform1.anchorY = 1
platform1.x = 450
platform1.y = yPosition()
physics.addBody(platform1, "static", {density=1, bounce=0.1, friction=1.0})
elements:insert(platform1)
end
.....
Maybe I have to add an onCollision function, to handle it?, or use joints? Any idea will be appreciated..
When you create a physics body, "static" body type means that bodies does not move under simulation and they behave as if they have infinite mass. Static bodies can be moved manually by the user, but they do not accept the application of velocity. Static bodies collide only with dynamic bodies, not with other static bodies or kinematic bodies.
(More details here: http://docs.coronalabs.com/api/type/Body/bodyType.html)
Try like this:
physics.addBody(player, "dynamic", {density=.1, bounce=0.1, friction=1.0})

remove all notes with same name

Hello I'm am using Marmalde Quick, so lua to create a game.
In my game when a park of the screen in tuched it creates a new note and add that note to physics.
function bgTouched(event)
if (director:getCurrentScene() == gameScene) then
if (gameState == gameStates.playing) then
if event.phase == "began" then
addToRoundScore()
if bodyType == 0 then
-- Create object1
b = director:createSprite(event.x, event.y, "textures/beachball.png")
b.name = "ball"
b.strokeWidth=0
b.xAnchor = 1; b.yAnchor = 0 -- test non-0 anchor point for circle
physics:addNode(b, {radius=40})
elseif bodyType == 1 then
-- Create object2
b = director:createSprite(event.x, event.y, "textures/crate.png")
b.name = "crate"
b.strokeWidth=0
b.xAnchor = 0; b.yAnchor = 0.5 -- test non-0 anchor point for rectangle
b.xScale = 2; b.yScale = 1 -- test different scale
physics:addNode(b, {} )
elseif bodyType == 2 then
-- Create obejct3
b = director:createSprite(event.x, event.y, "textures/triangle.png")
b.name = "tri"
b.xAnchor = 0.5; b.yAnchor = 1 -- test non-0 anchor point for polygon
physics:addNode(b, {shape={0,0, 95,0, 48,81}} )end
b.rotation = 22.5
bodyType = (bodyType + 1) % 3
end
end
end
end
bg:addEventListener ("touch", bgTouched)
when an event happens I want to remove all the notes created, I tried using the following:
physics:removeNode(b)
b:removeFromParent()
but this only removes the last created not I want to remove them all, is there some way to do this.
Thanks
If I understand right that you want to clear the nodes table before the event.phase == "began" processing where you add nodes, you could reset the physics table:
physics = {}
If other parts of code are referencing the physics node and they can't be notified that physics points to a new table, you could loop over all items of table and nil them:
for k,v in pairs(physics)
physics[k] = nil
end

Resources