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)
Related
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)
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 )
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.
This gear was inserted from the Catalog. It relocates the player to the center of the map when it's unequipped by clicking on the thumbnail. At 1st, I tested in a game I made. Everytime I unequipped it, the player kept falling through the baseplate and dying. I noticed it is the same position over and over. I moved the baseplate's position lower and the player falls down onto the baseplate instead of dying. Then I tested the gear in a new empty baseplate, unequipping it, the player moves to the center, too. I check the position of the both the Handle and the player's Torso, but that axis does not match any position in the script. Can someone point this out for me so that I can change it to the last position that the player stops?
Tool = script.Parent
Handle = Tool:WaitForChild("Handle")
Players = game:GetService("Players")
Debris = game:GetService("Debris")
Assets = require(Tool:WaitForChild("Assets"))
Data = Assets.Data
BaseUrl = Assets.BaseUrl
BasePart = Instance.new("Part")
BasePart.Material = Enum.Material.Plastic
BasePart.Shape = Enum.PartType.Block
BasePart.TopSurface = Enum.SurfaceType.Smooth
BasePart.BottomSurface = Enum.SurfaceType.Smooth
BasePart.FormFactor = Enum.FormFactor.Custom
BasePart.Size = Vector3.new(0.2, 0.2, 0.2)
BasePart.Anchored = false
BasePart.CanCollide = true
BasePart.Locked = true
Animations = {
Hold = {Animation = Tool:WaitForChild("Hold"), FadeTime = nil, Weight = nil, Speed = nil}
}
Sounds = {
Honk = Handle:WaitForChild("Honk"),
Engine = Handle:WaitForChild("Running")
}
Controls = {
Forward = {Key = "w", ByteKey = 17, Mode = false},
Backward = {Key = "s", ByteKey = 18, Mode = false},
Left = {Key = "a", ByteKey = 20, Mode = false},
Right = {Key = "d", ByteKey = 19, Mode = false}
}
Rate = (1 / 60)
Gravity = 196.20
PoseOffset = CFrame.new(0, -1.5125, -0.3) * CFrame.Angles(0, 0, 0) --The offset your character is from the center of the vehicle.
SpeedBoost = {
Allowed = false,
Active = false,
Enabled = true,
Duration = 10,
ReloadTime = 30
}
Special = {
Allowed = false,
Enabled = true,
Active = false,
Duration = 0,
ReloadTime = 60
}
Speed = {
Acceleration = {
Normal = 30,
Boost = 30
},
Deceleration = {
Normal = 30,
Boost = 30
},
MovementSpeed = {
Normal = {Min = 20, Max = 70},
Boost = {Min = 20, Max = 70}
},
TurnSpeed = {
Speed = {Min = 5, Max = 5},
TurnAlpha = 0.30,
AlphaDampening = 0.2
},
}
MaxSpeed = { --Maximum speed which the vehicle can move and turn at.
Movement = Speed.MovementSpeed.Normal,
Turn = Speed.TurnSpeed.Speed,
Acceleration = Speed.Acceleration.Normal,
Deceleration = Speed.Deceleration.Normal
}
CurrentSpeed = { --The speed which the vehicle is moving and turning at.
Movement = 0,
Turn = 0
}
Honk = {
Honking = false,
LastHonk = 0,
ReloadTime = 1
}
Jump = {
Jumping = false,
LastJump = 0,
ReloadTime = 1.25,
JumpForce = 30
}
ToolEquipped = false
ServerControl = (Tool:FindFirstChild("ServerControl") or Instance.new("RemoteFunction"))
ServerControl.Name = "ServerControl"
ServerControl.Parent = Tool
ClientControl = (Tool:FindFirstChild("ClientControl") or Instance.new("RemoteFunction"))
ClientControl.Name = "ClientControl"
ClientControl.Parent = Tool
Tool.Enabled = true
function RayCast(Position, Direction, MaxDistance, IgnoreList)
local IgnoreList = ((type(IgnoreList) == "table" and IgnoreList) or {IgnoreList})
return game:GetService("Workspace"):FindPartOnRayWithIgnoreList(Ray.new(Position, Direction.unit * (MaxDistance or 999.999)), IgnoreList)
end
function GetAllConnectedParts(Object)
local Parts = {}
local function GetConnectedParts(Object)
for i, v in pairs(Object:GetConnectedParts()) do
local Ignore = false
for ii, vv in pairs(Parts) do
if v == vv then
Ignore = true
end
end
if not Ignore then
table.insert(Parts, v)
GetConnectedParts(v)
end
end
end
GetConnectedParts(Object)
return Parts
end
function EnableFirstPersonView()
if not CheckIfAlive() or not ToolEquipped then
return
end
local Limbs = {"LeftHand", "RightHand"}
for i, v in pairs(Limbs) do
local Limb = Character:FindFirstChild(v)
if Limb:IsA("BasePart") then
Spawn(function()
InvokeClient("SetLocalTransparencyModifier", {Object = Limb, Transparency = 0, AutoUpdate = false})
end)
end
end
end
function ThrustUpdater()
for i, v in pairs(CurrentSpeed) do
CurrentSpeed[i] = 0
end
for i, v in pairs(Controls) do
Controls[i].Mode = false
end
while ToolEquipped and Body and Body.Parent and CheckIfAlive() and RotationForce and RotationForce.Parent and ThrustForce and ThrustForce.Parent and TurnGyro and TurnGyro.Parent do
RotationForce.angularvelocity = Vector3.new(0, CurrentSpeed.Turn, 0)
if math.abs(CurrentSpeed.Turn) > Speed.TurnSpeed.AlphaDampening then
CurrentSpeed.Turn = (CurrentSpeed.Turn - (Speed.TurnSpeed.AlphaDampening * (math.abs(CurrentSpeed.Turn) / CurrentSpeed.Turn)))
else
CurrentSpeed.Turn = 0
end
if not Controls.Forward.Mode or Controls.Backward.Mode then --Slow down if not controlling.
CurrentSpeed.Movement = (CurrentSpeed.Movement * 0.99)
end
local MySpeed = Vector3.new(Body.Velocity.X, 0, Body.Velocity.Z).magnitude
local VelocityDifference = math.abs((MySpeed - (ThrustForce.velocity.magnitude)))
if MySpeed > 3 and ThrustForce.velocity.magnitude > 3 and VelocityDifference > (0.7 * ThrustForce.velocity.magnitude) then
CurrentSpeed.Movement = (CurrentSpeed.Movement * 0.9)
end
if Controls.Forward.Mode then --Handle acceleration
CurrentSpeed.Movement = math.min(MaxSpeed.Movement.Max, (CurrentSpeed.Movement + (MaxSpeed.Acceleration * Rate)))
end
if Controls.Backward.Mode then --Handle deceleration, if speed is more than 0, decrease quicker.
CurrentSpeed.Movement = math.max(-MaxSpeed.Movement.Min, (CurrentSpeed.Movement - (MaxSpeed.Deceleration * ((CurrentSpeed.Movement > 0 and 2.8) or 1) * Rate)))
end
if Controls.Left.Mode then --Handle left turn speed
CurrentSpeed.Turn = math.min(Speed.TurnSpeed.Speed.Max, (CurrentSpeed.Turn + (Speed.TurnSpeed.TurnAlpha)))
end
if Controls.Right.Mode then --Handle right turn speed
CurrentSpeed.Turn = math.max(-Speed.TurnSpeed.Speed.Min, (CurrentSpeed.Turn - (Speed.TurnSpeed.TurnAlpha)))
end
local Direction = UpperTorso.CFrame.lookVector
Direction = Vector3.new(Direction.x, 0, Direction.z).unit
local Velocity = (Direction * CurrentSpeed.Movement) --The thrust force which you move.
ThrustForce.velocity = Vector3.new(Velocity.X, ThrustForce.velocity.Y, Velocity.Z)
local LeanAmount = (-CurrentSpeed.Turn * (math.pi / 6) / 4) --Amount your character leans over.
local XZAngle = math.atan2(UpperTorso.CFrame.lookVector.z, 0, UpperTorso.CFrame.lookVector.x) --Handle rotation
TurnGyro.cframe = CFrame.Angles((LeanAmount * Direction.x), 0, (LeanAmount * Direction.z))
--Wheel animation
local DesiredAngle = (999999999 * (-CurrentSpeed.Movement / math.abs(CurrentSpeed.Movement)))
local MaxVelocity = (CurrentSpeed.Movement / 250)
for i, v in pairs({FrontMotor, BackMotor}) do
if v and v.Parent then
v.DesiredAngle = DesiredAngle
v.MaxVelocity = MaxVelocity
end
end
--Smoke exhaust from vehicle running.
for i, v in pairs(ExhaustSmoke) do
if v and v.Parent then
v.Opacity = ((math.min(math.abs(CurrentSpeed.Movement), 10) / 10) * 0.5)
end
end
--Engine running sound which pitch changes while in motion.
Sounds.Engine.Pitch = (1 + (math.abs(CurrentSpeed.Movement / MaxSpeed.Movement.Max) * 1))
wait(Rate)
end
end
function SpawnVehicle()
Handle.Transparency = 1
Spawn(function()
InvokeClient("PlaySound", Sounds.Engine)
InvokeClient("PlayAnimation", Animations.Hold)
end)
Humanoid.PlatformStand = true
local VehicleData = Assets.CreateVehicle()
Body = VehicleData.Vehicle
local ParticleTable = VehicleData.Tables
--FrontMotor = Body.FrontMotor
--BackMotor = Body.BackMotor
ExhaustSmoke = ParticleTable.ExhaustSmoke
Lights = ParticleTable.Lights
Sparkles = ParticleTable.Sparkles
if SpeedBoost.Active then
for i, v in pairs(Sparkles) do
if v and v.Parent then
v.Enabled = true
end
end
end
local UpperTorsoWeld = Instance.new("Weld")
UpperTorsoWeld.C0 = PoseOffset
UpperTorsoWeld.Part0 = UpperTorso
UpperTorsoWeld.Part1 = Body
UpperTorsoWeld.Parent = Body
Body.CanCollide = true
RotationForce = Instance.new("BodyAngularVelocity")
RotationForce.maxTorque = Vector3.new(0, math.huge, 0)
RotationForce.angularvelocity = Vector3.new(0, 0, 0)
RotationForce.Parent = UpperTorso
ThrustForce = Instance.new("BodyVelocity")
ThrustForce.maxForce = Vector3.new(math.huge, 0, math.huge)
ThrustForce.velocity = Vector3.new(0, 0, 0)
ThrustForce.P = 100
ThrustForce.Parent = UpperTorso
TurnGyro = Instance.new("BodyGyro")
TurnGyro.maxTorque = Vector3.new(5000, 0, 5000)
TurnGyro.P = 300
TurnGyro.D = 100
TurnGyro.Parent = UpperTorso
Body.Parent = Tool
local RayHit, RayPos, RayNormal = RayCast(UpperTorso.Position, Vector3.new(0, -1, 0), (UpperTorso.Size.Y * 2), {Character})
if RayHit then
UpperTorso.CFrame = UpperTorso.CFrame + Vector3.new(0, ((Character:GetModelSize().Y / 2) + 1.5), 0)
end
Spawn(ThrustUpdater)
end
function FreezePlayer()
if CheckIfAlive() then
local FreezePart = BasePart:Clone()
FreezePart.Name = "FreezePart"
FreezePart.Transparency = 1
FreezePart.Anchored = true
FreezePart.CanCollide = false
local FreezeWeld = Instance.new("Weld")
FreezeWeld.Part0 = UpperTorso
FreezeWeld.Part1 = FreezePart
FreezeWeld.Parent = FreezePart
Debris:AddItem(FreezePart, 0.125)
FreezePart.Parent = Character
UpperTorso.Velocity = Vector3.new(0, -25, 0)
UpperTorso.RotVelocity = Vector3.new(0, 0, 0)
end
end
function CleanUp()
Handle.Velocity = Vector3.new(0, 0, 0)
Handle.RotVelocity = Vector3.new(0, 0, 0)
for i, v in pairs({}) do
if v then
v:disconnect()
end
end
for i, v in pairs({Body, RotationForce, ThrustForce, TurnGyro}) do
if v and v.Parent then
v:Destroy()
end
end
for i, v in pairs(Tool:GetChildren()) do
if v:IsA("BasePart") and v ~= Handle then
v:Destroy()
end
end
end
function CheckIfAlive()
return (((Character and Character.Parent and Humanoid and Humanoid.Parent and Humanoid.Health > 0 and UpperTorso and UpperTorso.Parent and Player and Player.Parent) and true) or false)
end
function Equipped(Mouse)
Character = Tool.Parent
Player = Players:GetPlayerFromCharacter(Character)
Humanoid = Character:FindFirstChild("Humanoid")
UpperTorso = Character:FindFirstChild("UpperTorso")
if not CheckIfAlive() then
return
end
Spawn(CleanUp)
Spawn(EnableFirstPersonView)
Spawn(SpawnVehicle)
ToolEquipped = true
end
function Unequipped()
Spawn(CleanUp)
Spawn(FreezePlayer)
for i, v in pairs(Sounds) do
v:Stop()
Spawn(function()
InvokeClient("StopSound", v)
end)
end
if CheckIfAlive() then
Humanoid.PlatformStand = false
end
Handle.Transparency = 0
ToolEquipped = false
end
function OnServerInvoke(player, mode, value)
if player == Player and ToolEquipped and value and CheckIfAlive() then
if mode == "KeyPress" then
local Down = value.Down
local Key = value.Key
local ByteKey = string.byte(Key)
for i, v in pairs(Controls) do
if Key == v.Key or ByteKey == v.ByteKey then
Controls[i].Mode = Down
end
end
if Key == " " and Down then --Jump controller
if math.abs(tick() - Jump.LastJump) > Jump.ReloadTime and not Jump.Jumping and ThrustForce and ThrustForce.Parent then
Jump.Jumping = true
local Parts = GetAllConnectedParts(Body)
local Mass = 0
for i, v in pairs(Parts) do
Mass = (Mass + v:GetMass())
end
ThrustForce.maxForce = Vector3.new(ThrustForce.maxForce.X, ((Mass * Gravity) * 100), ThrustForce.maxForce.Z)
ThrustForce.velocity = (Vector3.new(0, 1, 0) * Jump.JumpForce) + Vector3.new(ThrustForce.velocity.X, 0, ThrustForce.velocity.Z)
wait(0.1)
ThrustForce.maxForce = Vector3.new(ThrustForce.maxForce.X, 0, ThrustForce.maxForce.Z)
ThrustForce.velocity = Vector3.new(ThrustForce.velocity.X, 0, ThrustForce.velocity.Z)
Jump.LastJump = tick()
Jump.Jumping = false
end
elseif Key == "x" and Down then --Toggle light(s) on/off.
for i, v in pairs(Lights) do
if v and v.Parent then
v.Enabled = not v.Enabled
end
end
elseif Key == "h" and Down then --Play honk sound.
local Sound = Sounds.Honk
if (tick() - Honk.LastHonk) >= (Sound.TimeLength + Honk.ReloadTime) and not Honk.Honking then
Honk.Honking = true
local TempSound = Sound:Clone()
Debris:AddItem(TempSound, Sound.TimeLength)
TempSound.Parent = Body
TempSound:Play()
Honk.LastHonk = tick()
Honk.Honking = false
end
elseif Key == "q" and Down then --Activate special.
if not Special.Allowed or not Special.Enabled or Special.Active then
return
end
Special.Enabled = false
Special.Active = true
wait(Special.Duration)
Special.Active = false
wait(Special.ReloadTime)
Special.Enabled = true
elseif ByteKey == 48 and Down then --Activate speed boost.
if not SpeedBoost.Allowed or not SpeedBoost.Enabled or SpeedBoost.Active then
return
end
SpeedBoost.Enabled = false
SpeedBoost.Active = true
for i, v in pairs(Sparkles) do
if v and v.Parent then
v.Enabled = true
end
end
MaxSpeed.Acceleration = Speed.Acceleration.Boost
MaxSpeed.Deceleration = Speed.Deceleration.Boost
MaxSpeed.Movement = Speed.MovementSpeed.Boost
wait(SpeedBoost.Duration)
MaxSpeed.Acceleration = Speed.Acceleration.Normal
MaxSpeed.Deceleration = Speed.Deceleration.Normal
MaxSpeed.Movement = Speed.MovementSpeed.Normal
for i, v in pairs(Sparkles) do
if v and v.Parent then
v.Enabled = false
end
end
SpeedBoost.Active = false
wait(SpeedBoost.ReloadTime)
SpeedBoost.Enabled = true
end
end
end
end
function InvokeClient(Mode, Value)
local ClientReturn = nil
pcall(function()
ClientReturn = ClientControl:InvokeClient(Player, Mode, Value)
end)
return ClientReturn
end
Spawn(CleanUp)
ServerControl.OnServerInvoke = OnServerInvoke
Tool.Equipped:connect(Equipped)
Tool.Unequipped:connect(Unequipped)
I found it. Freezingplayer is the culprit. I took out "Spawn(FreezePlayer)" when it is unequipped and it works.
function Unequipped()
Spawn(CleanUp)
---Spawn(FreezePlayer)
I have a program where a player will be dodging falling asteroids, the asteroids will have to pass through the ground and hit each other without ending the game. However, if an asateroid hits a player the game will need to end and display the game over screen. How do I differentiate between the contacts.
Here is my code so far:
--Start the physics engine!
local physics = require ("physics")
--Get a background image!
local background = display.newImage("Images/Background.png")
-- Hide status bar
display.setStatusBar(display.HiddenStatusBar);
--Is this guy even alive?
local PlayerAlive = true;
--What size is our screen?
_H = display.contentHeight;
_W = display.contentWidth;
--Play some tunes!
local music = audio.loadStream("Sounds/bf3.mp3");
--World is flat and small!
local leftWall = display.newRect (0, 0, 1, display.contentHeight);
local rightWall = display.newRect (display.contentWidth, 0, 1, display.contentHeight);
physics.addBody (leftWall, "static", { bounce = 0.1 } );
physics.addBody (rightWall, "static", { bounce = 0.1 } );
leftWall.myName = "Left wall"
rightWall.myName = "Right wall"
--Discover Gravity!
physics.setGravity(0, 1)
--5 Random numbers!
local Rock1Y = Math.Random(20)
local Rock2Y = Math.Random(20)
local Rock3Y = Math.Random(20)
local Rock4Y = Math.Random(20)
local Rock5Y = Math.Random(20)
if (Rock1Y == Rock2Y)then
end
--Create our rock!
local MyRock1 = display.newImage("Images/Rock.png", 25, 25)
local MyRock2 = display.newImage("Images/Rock.png", 25, 25)
local MyRock3 = display.newImage("Images/Rock.png", 25, 25)
local MyRock4 = display.newImage("Images/Rock.png", 25, 25)
local MyRock5 = display.newImage("Images/Rock.png", 25, 25)
--Add physics to our rock!
physics.addBody(MyRock1, "dynamic", {density = 1, friction = 0.0, bounce = 0.9, radius=10)
MyRock1.myName = "Rock 1"
physics.addBody(MyRock2, "dynamic", {density = 1, friction = 0.0, bounce = 0.9, radius=10)
MyRock2.myName = "Rock 2"
physics.addBody(MyRock3, "dynamic", {density = 1, friction = 0.0, bounce = 0.9, radius=10)
MyRock3.myName = "Rock 3"
physics.addBody(MyRock4, "dynamic", {density = 1, friction = 0.0, bounce = 0.9, radius=10)
MyRock4.myName = "Rock 4"
physics.addBody(MyRock5, "dynamic", {density = 1, friction = 0.0, bounce = 0.9, radius=10)
MyRock5.myName = "Rock 5"
--Where should MyRock be?
MyRock1.x = Random(10, _W-50) --Rock 1
MyRock1.y = Random(_H+Rock1Y)
MyRock2.x = Random(10, _W-50) --Rock 2
MyRock2.y = Random(_H+Rock2Y)
MyRock3.x = Random(10, _W-50) --Rock 3
MyRock3.y = Random(_H+Rock3Y)
MyRock4.x = Random(10, _W-50) --Rock 4
MyRock4.y = Random(_H+Rock4Y)
MyRock5.x = Random(10, _W-50) --Rock 5
MyRock5.y = Random(_H+Rock5Y)
--Here goes the character!
local character = display.newImage("Images/Character.png", display.contentWidth/2, 0)
physics.addBody(character, "dynamic", {density = 0, friction = 0.0, bounce = 0.9, radius = 2)
character.myName = "Character"
--Check for collision with character
local function onCollision( event )
if ( event.phase == "began" ) then
--IF THE PLAYER IS HIT ADD THIS CODE BRENDAN DO IT TONIGHT
end
end
the collision event object has information about the objects that collided. You could do something like this:
if event.object1 == character or event.object2 == character then
print( "character was hit!" )
--end game and display game over code
end
Read more here:
http://docs.coronalabs.com/api/event/collision/index.html