How to make arms and tools stay on screen in Roblox studio? - lua

In games like phantom forces, or any FPS for that matter, if you look up or down, the arms and tools will stay on screen. In a new Roblox studio project, this does not happen by default. Basically I want the arms and tools to follow the camera’s rotation.

This can be done, but do you want other players to see the player turn the gun towards the camera?
local Camera = workspace.CurrentCamera
local Player = game.Players.LocalPlayer
local Character = workspace:WaitForChild(Player.Name)
local Root = Character:WaitForChild("HumanoidRootPart")
local Neck = Character:WaitForChild("UpperTorso"):FindFirstChildOfClass("Motor6D")
local YOffset = Neck.C0.Y
local CFNew, CFAng = CFrame.new, CFrame.Angles
local asin = math.asin
game:GetService("RunService").RenderStepped:Connect(function()
local CameraDirection = Root.CFrame:toObjectSpace(Camera.CFrame).lookVector
if Neck then
if Character.Humanoid.RigType == Enum.HumanoidRigType.R15 then
Neck.C0 = CFNew(0, YOffset, 0) * CFAng(0, -asin(CameraDirection.x), 0) * CFAng(asin(CameraDirection.y), 0, 0)
elseif Character.Humanoid.RigType == Enum.HumanoidRigType.R6 then
Neck.C0 = CFNew(0, YOffset, 0) * CFAng(3 * math.pi/2, 0, math.pi) * CFAng(0, 0, -asin(CameraDirection.x)) * CFAng(-asin(CameraDirection.y), 0, 0)
end
end
end)
This example only works with R15
If you don't want the players to see this, then create a model of the gun from the client's side and stick it on the camera
local Camera = workspace.CurrentCamera
local Player = game.Players.LocalPlayer
local Character = workspace:WaitForChild(Player.Name)
local Root = Character:WaitForChild("HumanoidRootPart")
NAMES = {
screen_gun = "Local_Gun",
model= "Gun",
view = "view"
}
--- For Player
local Gun = {
screen = Instance.new("ScreenGui",Player:FindFirstChildOfClass("PlayerGui")),
obj=Instance.new("ViewportFrame",Player:FindFirstChildOfClass("PlayerGui"):WaitForChild("ScreenGui")),
part =Instance.new("Part",Player:WaitForChild("PlayerGui"):WaitForChild("ScreenGui"):WaitForChild("ViewportFrame")),
mesh = Instance.new("SpecialMesh",Player:WaitForChild("PlayerGui"):WaitForChild("ScreenGui"):WaitForChild("ViewportFrame"):WaitForChild("Part")),
offset = UDim2.new(0.7,0,0.6,0),
cam = Instance.new("Camera",Player:WaitForChild("PlayerGui"):WaitForChild("ScreenGui"):WaitForChild("ViewportFrame")),
offset2 = CFrame.new(Vector3.new(1,1,1),Vector3.new(0,0,0)),
size_view = UDim2.new(0,300,0,300)
}
Gun.obj.CurrentCamera=Gun.cam
Gun.part.Position = Vector3.new(0,0,0)
Gun.obj.Position = Gun.offset
Gun.obj.Size = Gun.size_view
Gun.obj.BackgroundTransparency = 1
Gun.cam.CFrame = Gun.offset2
Gun.screen.Name = NAMES.screen_gun
Gun.part.Name = NAMES.model
Gun.obj.Name = NAMES.view
Gun.part.Size = Vector3.new(1,1,2)
--
Gun.obj.Visible = false
local ToolInHand = false
Character.ChildAdded:Connect(function(obj)
if obj:IsA("Tool") and ( obj:FindFirstChildOfClass("Part") or obj:FindFirstChildOfClass("MeshPart") ) then --
if obj:FindFirstChildOfClass("MeshPart") then
obj:FindFirstChildOfClass("MeshPart").LocalTransparencyModifier = 1
Gun.mesh.MeshId = obj:FindFirstChildOfClass("MeshPart").MeshId
elseif obj:FindFirstChildOfClass("Part") then
obj:FindFirstChildOfClass("Part").LocalTransparencyModifier = 1
end
Gun.obj.Visible = true
ToolInHand = true
end
end)
Character.ChildRemoved:Connect(function(obj)
if obj:IsA("Tool") and ( obj:FindFirstChildOfClass("Part") or obj:FindFirstChildOfClass("MeshPart") ) then
if obj:FindFirstChildOfClass("MeshPart") then
obj:FindFirstChildOfClass("MeshPart").LocalTransparencyModifier = 0
elseif obj:FindFirstChildOfClass("Part") then
obj:FindFirstChildOfClass("Part").LocalTransparencyModifier = 0
end
Gun.obj.Visible = false
ToolInHand = false
end
end)

Related

Roblox, how to make something only tween in one direction?

I tried doing
local fakeRightArm = Instance.new("Part")
fakeRightArm.BottomSurface = Enum.SurfaceType.Smooth
fakeRightArm.CanCollide = false
fakeRightArm.Massless = true
fakeRightArm.Material = Enum.Material.Plastic
fakeRightArm.BrickColor = RightArm.BrickColor
fakeRightArm.Size = RightArm.Size
fakeRightArm.CFrame = RightArm.CFrame
fakeRightArm.Parent = character
fakeRightArm.Name = "fakeRightArm"
local weld = Instance.new("WeldConstraint")
weld.Part0 = RightArm
weld.Part1 = fakeRightArm
weld.Parent = character
weld.Name = "FakeArmWeld"
tweenService:Create(fakeRightArm, TweenInfo.new(0.3, Enum.EasingStyle.Quad), {Size = fakeRightArm.Size + Vector3.new(0, 50, 0), CFrame = fakeRightArm.CFrame * CFrame.new(0,0,-50)}):Play()
but that seems to not work. It's probably because of the weld.
I want it so it tweens the arm forward.
DevForum post (maybe more detailed): https://devforum.roblox.com/t/how-to-only-tween-in-one-direction/841408/42
Thank you!
don't think you need the tween function just to position it
https://developer.roblox.com/en-us/api-reference/datatype/CFrame
start with the right arm position, then rotate its coordinate frame.
local fakeRightArm = Instance.new("Part")
fakeRightArm.BottomSurface = Enum.SurfaceType.Smooth
fakeRightArm.CanCollide = false
fakeRightArm.Massless = true
fakeRightArm.Material = Enum.Material.Plastic
fakeRightArm.BrickColor = RightArm.BrickColor
fakeRightArm.Size = RightArm.Size
fakeRightArm.Parent = character
fakeRightArm.Anchored = true
fakeRightArm.Name = "fakeRightArm"
-- you pick which angle to make it face
local Xdir = math.rad( 0 ) -- twist palm up, palm down
local Ydir = math.rad( 90 ) -- lift up / down
local Zdir = math.rad( 15 ) -- swing left / right
fakeRightArm.CFrame = RightArm.Position *CFrame.Angles( Xdir, Ydir, Zdir )

How to make a smooth projectile in roblox?

I am trying to make a projectile (Energy ball) for my game. I am using body velocities, but the issue is is that it seems laggy. I shoot it then half a second through flight it seems to stop in mid air for a quarter of a second then continue. This only happens the first minute of playing.
I tested shooting at the ground so at an angle so it will go slower, but it seems the the ball freezes when it reaches a certain distance from the player, not a certain time.
The actual projectile is a less transparent ball inside of a bigger, more transparent ball, connected by a weld. If I remove one of the balls so the projectile is just one ball, my issue is gone. How can I remove the issue while keeping both balls?
Here is my code that I tried:
EnergyBallEvent.OnServerEvent:Connect(function(Player, MouseClickLocation)
local Character = Player.Character
local Humanoid = Character:FindFirstChildWhichIsA("Humanoid")
if Humanoid.Health > 0 and not DisabledItems[Player.UserId..'EnergyBall'] then
DisabledItems[Player.UserId..'EnergyBall'] = true
Humanoid:LoadAnimation(script.EnergyBallAnimation):Play()
local Ball = Instance.new("Part", SpellsFolder)
local CasterValue = Instance.new("ObjectValue", Ball)
CasterValue.Name = "Caster"
CasterValue.Value = Player.Character
Ball:SetNetworkOwner(nil) --removing or modifying this
Ball.Transparency = 1
Ball.Shape = Enum.PartType.Ball
Ball.BrickColor = BrickColor.new(0, 255, 255)
Ball.Material = Enum.Material.Neon
Ball.Size = Vector3.new(2.2, 2.2, 2.2)
Ball.Massless = true
Ball.CanCollide = false
local Weld = Instance.new("Weld", Ball)
Weld.Part0 = Ball
Ball = Instance.new("Part", Ball)
Ball:SetNetworkOwner(nil) --or this have no effect that is visible
Ball.Transparency = 1
Ball.Shape = Enum.PartType.Ball
Ball.BrickColor = BrickColor.new(0, 255, 255)
Ball.Material = Enum.Material.Neon
Ball.Size = Vector3.new(1.6, 1.6, 1.6)
Ball.Massless = true
Weld.Part1 = Ball
Weld = Instance.new("Weld", Ball)
Weld.Part0 = Ball
if Character:FindFirstChild("LeftHand") then
Weld.Part1 = Character.LeftHand
else
end
for i = 0, 40, 1 do
Ball.Transparency = Ball.Transparency - 0.012
Ball.Parent.Transparency = Ball.Parent.Transparency - 0.006
wait(0.02)
end
Weld:Destroy()
local Motion = Instance.new("BodyVelocity", Ball)
Motion.Velocity = ((MouseClickLocation - Player.Character.HumanoidRootPart.Position).Unit*100)
DisabledItems[Player.UserId..'EnergyBall'] = nil
end
end)
Here is some more code I tried:
EnergyBallEvent.OnServerEvent:Connect(function(Player, MouseClickLocation)
local Character = Player.Character
local Humanoid = Character:FindFirstChildWhichIsA("Humanoid")
if Humanoid.Health > 0 and not DisabledItems[Player.UserId..'EnergyBall'] then
DisabledItems[Player.UserId..'EnergyBall'] = true
Humanoid:LoadAnimation(script.EnergyBallAnimation):Play()
local Model = Instance.new("Model", SpellsFolder)
local Ball = Instance.new("Part", Model)
local CasterValue = Instance.new("ObjectValue", Model)
CasterValue.Name = "Caster"
CasterValue.Value = Player.Character
Ball.Transparency = 1
Ball.Shape = Enum.PartType.Ball
Ball.BrickColor = BrickColor.new(0, 255, 255)
Ball.Material = Enum.Material.Neon
Ball.Size = Vector3.new(2.2, 2.2, 2.2)
Ball.Massless = true
Ball.CanCollide = false
local Weld = Instance.new("Weld", Ball)
Weld.Part0 = Ball
local Ball2 = Instance.new("Part", Model)
Model.PrimaryPart = Ball2
Ball2:SetNetworkOwner(nil)
Ball2.Transparency = 1
Ball2.Shape = Enum.PartType.Ball
Ball2.BrickColor = BrickColor.new(0, 255, 255)
Ball2.Material = Enum.Material.Neon
Ball2.Size = Vector3.new(1.6, 1.6, 1.6)
Ball2.Massless = true
Weld.Part1 = Ball2
Weld = Instance.new("Weld", Ball2)
Weld.Part0 = Ball2
if Character:FindFirstChild("LeftHand") then
Weld.Part1 = Character.LeftHand
else
end
for i = 0, 40, 1 do
Ball2.Transparency = Ball2.Transparency - 0.012
Ball.Transparency = Ball.Transparency - 0.006
wait(0.02)
end
Weld:Destroy()
local Motion = Instance.new("BodyVelocity", Ball)
Motion.Velocity = ((MouseClickLocation - Player.Character.HumanoidRootPart.Position).Unit*100)
DisabledItems[Player.UserId..'EnergyBall'] = nil
end
end)
I hate this behaviour and I NEED to fix it
Another observation is if I comment out the second ball creation and stuff so it is a just one ball, the bug is gone
You want to add the propulsion code to the clientside script in an OnClientEvent:Connect() block, and make the serverscript instead have Ball:SetNetworkOwner(Player) and EnergyBallEvent:FireClient(Ball). I'm OP but I might as well answer this question now since I figured it out long ago.

Xonix Game Optimization Problems

I'm doing a Xonix game on corona sdk. As a playing field, I decided to use a grid of squares. Width 44, Height 71. As a result, I received a row consisting of 3124(44*71) squares along which the player moves. But I have problems with optimization. The engine can not cope with such a number of squares on the screen at the same time. Because of this, FPS on a smartphone is not more than 12. Help me find the best solution. All that concerns polygons and meshes, I am not strong in geometry ((((
Reducing the number of squares is a bad idea. Then the appearance is lost, and the field is captured too large pieces.
Thank you in advance!
-- Creating a playing field
M.create_pole = function()
-- init
local image = display.newImage
local rect = display.newRect
local rrect = display.newRoundedRect
local floor = math.floor
M.GR_ZONE = display.newGroup()
M.POLE = {}
-- bg
M.POLE.bg = rrect(0,0,150,150,5)
M.POLE.bg.width = M.width_pole
M.POLE.bg.height = M.height_pole
M.POLE.bg.x = _W/2
M.POLE.bg.y = _H/2
M.POLE.bg.xScale = _H*.00395
M.POLE.bg.yScale = _H*.00395
M.POLE.bg:setFillColor(API.hexToCmyk(M.color.land))
M.GR:insert(M.POLE.bg)
M.POLE.img = image(IMAGES..'picture/test.jpg')
M.POLE.img.width = M.width_pole-M.size_xonix
M.POLE.img.height = M.height_pole-M.size_xonix
M.POLE.img.x = _W/2
M.POLE.img.y = _H/2
M.POLE.img.xScale = _H*.00395
M.POLE.img.yScale = _H*.00395
M.POLE.img.strokeWidth = 1.3
M.POLE.img:setStrokeColor(API.hexToCmyk(M.color.img))
M.GR:insert(M.POLE.img)
-- control player
M.POLE.bg:addEventListener( 'touch', M.swipe )
M.POLE.bg:addEventListener( 'tap', function(e)
M.POLE.player.state = 0
end )
-- arr field
M.arr_pole = {} -- newRect
local jj = 0
for i=1,M.delta_height do -- 71 point
M.arr_pole[i] = {}
M.GUI.border[i] = {}
for k=1,M.delta_width do -- 44 point
jj = jj+1
M.arr_pole[i][k] = {nm = jj}
M.GUI.border[i][k] = {}
local xx = k*M.size_xonix
local yy = i*M.size_xonix
local _x = floor(xx-M.size_xonix/2)
local _y = floor(yy-M.size_xonix/2)
M.arr_pole[i][k][1] = image(IMAGES..'pole/land.jpg')
M.arr_pole[i][k][1] .x = _x
M.arr_pole[i][k][1] .y = _y
M.GR_ZONE:insert(M.arr_pole[i][k][1])
-- water at the edges
-- the rest is land
if (i==1 or i==M.delta_height)
or (k==1 or k==M.delta_width) then
M.arr_pole[i][k].type = 0
else
M.arr_pole[i][k].type = 2
M.arr_pole[i][k][1].isVisible = true
end
end
end
M.GR_ZONE.width = M.POLE.bg.width*M.POLE.bg.xScale
M.GR_ZONE.height = M.POLE.bg.height*M.POLE.bg.yScale
M.GR_ZONE.x = M.POLE.bg.x-M.POLE.bg.width*M.POLE.bg.xScale/2
M.GR_ZONE.y = M.POLE.bg.y-M.POLE.bg.height*M.POLE.bg.yScale/2
-- player
local _x = M.arr_pole[1][1][1].x
local _y = M.arr_pole[1][1][1].y
M.POLE.player = image(IMAGES..'ui/player.png')
M.POLE.player.x = _x
M.POLE.player.y = _y
M.POLE.player.width = M.size_xonix*1.5
M.POLE.player.height = M.size_xonix*1.5
M.POLE.player.state = 0
M.GR_ZONE:insert(M.POLE.player)
M.POLE.player:toFront()
end
-- get all free cells
- land
M.get_free = function(_i,_j,_start)
local _par = pairs
local _fill = M.filling_arr
local _arr = M.arr_pole
local _index = {
{-1,-1}, {0,-1}, {1,-1},
{-1, 0}, {1, 0},
{-1, 1}, {0, 1}, {1, 1},
}
-- mark as verified
_arr[_i][_j].is_check = true
_fill[#_fill+1] = {_i,_j}
for k,v in _par(_index) do
local i = _i+v[1]
local j = _j+v[2]
if i>1 and i<M.delta_height
and j>1 and j<M.delta_width then
if not _arr[i][j].is_check then
if _arr[i][j].type==2 then
M.get_free(i,j)
end
end
end
end
if _start then
return _fill
end
end
-- fill(capture)
M.filling = function()
-- init
local par = pairs
local tb_rem = table.remove
local arr = M.arr_pole
M.island_arr = {}
-- check indicator
for i,ii in par(arr) do
for j,jj in par(ii) do
if jj.type==2 then
jj.is_check = false
end
end
end
-- we divide land into islands
for i,ii in par(arr) do
for j,jj in par(ii) do
if jj.type==2 and not jj.is_check then
M.filling_arr = {}
M.island_arr[#M.island_arr+1] = M.get_free(i,j,true)
end
end
end
- find a larger island and delete it
local sel_max = {dir = '', count = 1}
for k,v in par(M.island_arr) do
if #v>=sel_max.count then
sel_max.dir = k
sel_max.count = #v
end
end
if #M.island_arr>0 then
tb_rem(M.island_arr,sel_max.dir)
end
-- fill
for k,v in par(M.island_arr) do
for kk,vv in par(v) do
local obj = arr[vv[1]][vv[2]]
obj.type = 0
obj[1].isVisible = false
end
end
-- turning the edges into water
for k,v in par(M.bread_crumbs) do
local arr = arr[v.arr_y][v.arr_x]
arr.type = 0
arr[1].isVisible = false
end
M.clear_history()
end

ROBLOX - Why is this fly script working only in the Studio?

I really need help..
I have this code for fly, as a backpack item:
Name = "Fly"
pi = 3.141592653589793238462643383279502884197163993751
a = 0
s = 0
ndist = 13
rs = 0.025
siz = Vector3.new(1, 1, 1)
form = 0
flow = {}
function CFC(P1,P2)
local Place0 = CFrame.new(P1.CFrame.x,P1.CFrame.y,P1.CFrame.z)
local Place1 = P2.Position
P1.Size = Vector3.new(P1.Size.x,P1.Size.y,(Place0.p - Place1).magnitude)
P1.CFrame = CFrame.new((Place0.p + Place1)/2,Place0.p)
end
function checktable(table, parentneeded)
local i
local t = {}
for i = 1, #table do
if table[i] ~= nil then
if string.lower(type(table[i])) == "userdata" then
if parentneeded == true then
if table[i].Parent ~= nil then
t[#t + 1] = table[i]
end
else
t[#t + 1] = table[i]
end
end
end
end
return t
end
if script.Parent.Name ~= Name then
User = game:service("Players").Nineza
HB = Instance.new("HopperBin")
HB.Name = Name
HB.Parent = User.StarterGear
script.Parent = HB
User.Character:BreakJoints()
end
speed = 50
script.Parent.Selected:connect(function(mar)
s = 1
torso = script.Parent.Parent.Parent.Character.Torso
LeftShoulder = torso["Left Shoulder"]
RightShoulder = torso["Right Shoulder"]
LeftHip = torso["Left Hip"]
RightHip = torso["Right Hip"]
human = script.Parent.Parent.Parent.Character.Humanoid
bv = Instance.new("BodyVelocity")
bv.maxForce = Vector3.new(0,math.huge,0)
bv.velocity = Vector3.new(0,0,0)
bv.Parent = torso
bg = Instance.new("BodyGyro")
bg.maxTorque = Vector3.new(0,0,0)
bg.Parent = torso
connection = mar.Button1Down:connect(function()
a = 1
bv.maxForce = Vector3.new(math.huge,math.huge,math.huge)
bg.maxTorque = Vector3.new(900000,900000,900000)
bg.cframe = CFrame.new(torso.Position,mar.hit.p) * CFrame.fromEulerAnglesXYZ(math.rad(-90),0,0)
bv.velocity = CFrame.new(torso.Position,mar.hit.p).lookVector * speed
moveconnect = mar.Move:connect(function()
bg.maxTorque = Vector3.new(900000,900000,900000)
bg.cframe = CFrame.new(torso.Position,mar.hit.p) * CFrame.fromEulerAnglesXYZ(math.rad(-90),0,0)
bv.velocity = CFrame.new(torso.Position,mar.hit.p).lookVector * speed
end)
upconnect = mar.Button1Up:connect(function()
a = 0
moveconnect:disconnect()
upconnect:disconnect()
bv.velocity = Vector3.new(0,0,0)
bv.maxForce = Vector3.new(0,math.huge,0)
torso.Velocity = Vector3.new(0,0,0)
bg.cframe = CFrame.new(torso.Position,torso.Position + Vector3.new(torso.CFrame.lookVector.x,0,torso.CFrame.lookVector.z))
wait(1)
end)
end)
while s == 1 do
wait(0.02)
flow = checktable(flow, true)
local i
for i = 1,#flow do
flow[i].Transparency = flow[i].Transparency + rs
if flow[i].Transparency >= 1 then flow[i]:remove() end
end
if a == 1 then
flow[#flow + 1] = Instance.new("Part")
local p = flow[#flow]
p.formFactor = form
p.Size = siz
p.Anchored = true
p.CanCollide = false
p.TopSurface = 0
p.BottomSurface = 0
if #flow - 1 > 0 then
local pr = flow[#flow - 1]
p.Position = torso.Position - torso.Velocity/ndist
CFC(p, pr)
else
p.CFrame = CFrame.new(torso.Position - torso.Velocity/ndist, torso.CFrame.lookVector)
end
p.BrickColor = BrickColor.new("Cyan")
p.Transparency = 1
p.Parent = torso
local marm = Instance.new("BlockMesh")
marm.Scale = Vector3.new(1.9, 0.9, 1.725)
marm.Parent = p
local amplitude
local frequency
amplitude = pi
desiredAngle = amplitude
RightShoulder.MaxVelocity = 0.4
LeftShoulder.MaxVelocity = 0.4
RightHip.MaxVelocity = pi/10
LeftHip.MaxVelocity = pi/10
RightShoulder.DesiredAngle = desiredAngle
LeftShoulder.DesiredAngle = -desiredAngle
RightHip.DesiredAngle = 0
LeftHip.DesiredAngle = 0
end
end
end)
script.Parent.Deselected:connect(function()
a = 0
s = 0
bv:remove()
bg:remove()
if connection ~= nil then
connection:disconnect()
end
if moveconnect ~= nil then
moveconnect:disconnect()
end
if upconnect ~= nil then
upconnect:disconnect()
end
while s == 0 do
wait()
if #flow > 0 then
flow = checktable(flow, true)
local i
for i = 1,#flow do
flow[i].Transparency = flow[i].Transparency + rs
if flow[i].Transparency >= 1 then flow[i]:remove() end
end
end
end
end)
while true do
wait()
if s == 1 then
return
end
end
script:remove()
The script is in a HopperBin Object in the game's StarterPack Folder.
Now if you try it on your own, you'll see that it will work, BUT if you publish the game, play it via ROBLOX(not the studio) and try to use the item, you won't fly.
Any ideas why?
It's been a long time since I haven't played ROBLOX, so my answer might be inaccurate.
First, you need to understand the difference between a Script and a Localscript. In a nutshell, a script runs server-side whereas a Localscript runs client-side. Your fly script is expected to run on a player's client, thus you have to use a Localscript.
Your regular script works in build-mode because scripts are run on your client, and thus are considered as Localscripts. When you publish your game and play it, your computer doesn't work as a server anymore, but as a client.
In addition to this, as you use a localscript, you may have to change the following line :
-- gets the client (local player) on which the script is running
User = Game:GetService("Players").LocalPlayer
Also, avoid relative paths such as script.Parent.Parent.Parent..... You want to get the client's torso, so just use your User variable as per : User.Character.Torso. Do the same for the character's Humanoid object.
I think it's because the time to load not existing try this at line1:
repeat wait() until game.Players.LocalPlayer.Character

corona set physics limitation

How can I make my game character's physic is limited only to 'tilt' left and right a bit? Here's how I declared my character
collector = display.newImage ("ms_throw.png")
collector.x = 10
collector.y = 10
physics.addBody(collector, {friction = 1.0, bounce = 0.6})
ms_throw.png is an image of a man standing... so basically collector will move left to right (using accelerometer) and I need the actor to only tilt a bit when he's moving.. means I don't want it to turn upside down when I tilt the phone.. How do I achieve this?
The trick is to tweak the coordinatey of applyForce(forcex,forcey,coordinatex,coordinatey).
If there is significant friction, the object will tilt.
To limit the tilt angle, use a box to cage it.
local physics = require("physics")
physics.start()
physics.setGravity(0,10)
centerx = display.viewableContentWidth/2+(display.contentWidth-display.viewableContentWidth)/2
centery = display.viewableContentHeight/2+(display.contentHeight-display.viewableContentHeight)/2
borderx = (display.contentWidth-display.viewableContentWidth)/2
bordery = (display.contentHeight-display.viewableContentHeight)/2
local w = display.viewableContentWidth/2
local h = 100/2
local allowanceHeight = 15
local collectorLimiter = {}
--cannot do in createScene because need to do together with physics
local ix,iy = centerx,bordery+display.viewableContentHeight-60
collectorLimiter[1] = display.newRect(0,0,display.viewableContentWidth,4)
collectorLimiter[1].x,collectorLimiter[1].y = ix,iy-h-allowanceHeight
collectorLimiter[2] = display.newRect(0,0,display.viewableContentWidth,4)
collectorLimiter[2].x,collectorLimiter[2].y = ix,iy+h
collectorLimiter[3] = display.newRect(0,0,4,h*2+allowanceHeight)
collectorLimiter[3].x,collectorLimiter[3].y = ix-w,iy
collectorLimiter[4] = display.newRect(0,0,4,h*2+allowanceHeight)
collectorLimiter[4].x,collectorLimiter[4].y = ix+w,iy
for i = 1,#collectorLimiter do
--collectorLimiter[i].isVisible = false
end
physics.addBody(collectorLimiter[1],"static", {friction = 0.3,bounce = 0, filter = {categoryBits = 4,maskBits = 6} })
physics.addBody(collectorLimiter[2],"static", {friction = 0.3,bounce = 0, filter = {categoryBits = 4,maskBits = 6} })
physics.addBody(collectorLimiter[3],"static", {friction = 0.3,bounce = 0, filter = {categoryBits = 4,maskBits = 6} })
physics.addBody(collectorLimiter[4],"static", {friction = 0.3,bounce = 0, filter = {categoryBits = 4,maskBits = 6} })
local collector = display.newRect(0,0,80,100)
collector.x,collector.y = centerx,centery+480
physics.addBody(collector, {friction = 0.3, density = 0.2, bounce = 0, filter = {categoryBits = 2}} )
local function OnTouch(event)
-- Move our collector based on the accelerator values
if event.phase == "began" then
collector.ix,collector.iy = event.x,event.y
elseif event.phase == "moved" then
if collector.ix and collector.iy then
local dx = (event.x-collector.ix)*0.4
collector:applyForce(dx,0,collector.x,collector.y-10)
collector.ix,collector.iy = collector.x,collector.y
end
elseif event.phase == "ended" or event.phase == "cancelled" then
collector.ix,collector.iy = nil,nil
end
end
Runtime:addEventListener("touch",OnTouch)

Resources