Not sure how to use vector3 - lua

I tried to make an item spawn every 60 seconds and in one of two locations, but when I tried to use vector3 it didn't spawn in the location of the "spawnplace1" or "spawnplace2", but it spawned ontop of the roka being copied and didn't move. Also I don't think I can hold the copied roka's either. Here's the code!
local roka = workspace["Rokakaka Fruit"]
local itemspawns = workspace.ItemSpawnLocals
local itemspawn1 = itemspawns["Item Spawn 1"]
local itemspawn2 = itemspawns["Item Spawn 2"]
local place1 = itemspawn1.Position
local place2 = itemspawn2.Position
wait(60)
local spawnplace1 = math.random(1,2)
local spawnplace2 = math.random(1,2)
if spawnplace1 == 1 then
roka2 = roka:Clone()
roka2.Parent = workspace
local roka2handle = roka2.Handle
roka2handle.Position = Vector3.new(itemspawn1)
elseif spawnplace1 == 2 then
roka2 = roka:Clone()
roka2.Parent = workspace
local roka2handle = roka2.Handle
roka2handle.Position = Vector3.new(itemspawn2)
end
print(spawnplace1)
print(spawnplace2)

The Vector3 holds coordinates of a point in 3D space. You have only provided 1 of 3 pieces of information in the constructor. To construct a Vector3, you need to provide the Y and Z axes as well, like this :
roka2handle.Position = Vector3.new(1, 2, 3)
But you don't need to explicitly create a Vector3 to get your code working. You can just assign the positions of the spawn locations to your newly created fruit, and that should do the trick. This way, you can add lots more spawn locations, and you don't need to update the script each time.
-- grab some things from the workspace
local roka = workspace["Rokakaka Fruit"]
local itemSpawns = workspace.ItemSpawnLocals
-- choose a random spawn location
local spawnLocations = itemSpawns:GetChildren()
local spawnNumber = math.random(1, #spawnLocations)
local spawnPosition = spawnLocations[spawnNumber].Position
-- spawn and move a new fruit to one of the spawn locations
roka2 = roka:Clone()
roka2.Parent = workspace
local roka2handle = roka2.Handle
roka2handle.Position = spawnPosition
-- debug
print("spawning fruit at : ", spawnPosition)
As a side note, if roka2 is a Model, you may want to consider using roka2:SetPrimaryPartCFrame( CFrame.new(spawnPosition)) to move it around.

Related

Roblox Item is lagging

I add a mesh to follow the player where ever he goes. But the mesh is lagging a bit when the player runs. I understand that it is not rendering quickly enough, but anyone know how to add a mesh without it lagging?
local humanoidRootPart = character:WaitForChild('HumanoidRootPart')
local backpackItemWorkspace = game.ReplicatedStorage.Meshes[pet.Name]:Clone()
backpackItemWorkspace.Parent = game.Workspace.CurrentPets
RunService.Stepped:Connect(function()
local location = humanoidRootPart.CFrame
backpackItemWorkspace.CFrame = location * CFrame.new(2, 2, 3)
end)
Connect the mesh and rootpart using a weld, so you dont need to use RunService to move the mesh everytime.
local humanoidRootPart = character:WaitForChild('HumanoidRootPart')
local backpackItemWorkspace = game.ReplicatedStorage.Meshes[pet.Name]:Clone()
backpackItemWorkspace.Parent = game.Workspace.CurrentPets
function attach(hroot, mesh)
local weld = Instance.new("WeldConstraint", mesh)
local location = hroot.CFrame
mesh.CFrame = location + Vector3.new(2, 2, 3)
weld.Part0 = hroot
weld.Part1 = mesh
return weld
end
attach(humanoidRootPart, backpackItemWorkspace)
-- please comment if it makes any errors
Ok, for others struggling with having a pet(mesh) follow you smoothly and always stay on your back. I have now spent several hours on this subject and finally got it to work. This is how you do it:
local character = player.Character
local humanoidRootPart = character:WaitForChild('HumanoidRootPart')
//where you copy you pet from
local backpackItemWorkspace = game.ReplicatedStorage.Meshes[pet.Name]:Clone()
//where you keep your pets in the workspace
backpackItemWorkspace.Parent = game.Workspace.CurrentPets
//call the function for attaching the pet
attachPet(backpackItemWorkspace, character, humanoidRootPart)
function attachPet (pet, char, humanoidRootPart)
local focusPart = humanoidRootPart
local newPet = pet
local z = -5
local x = 1
local bodyPos = Instance.new("BodyPosition")
bodyPos.Parent = newPet
bodyPos.MaxForce = Vector3.new(math.huge, math.huge, math.huge)
local bodyGyro = Instance.new("BodyGyro")
bodyGyro.Parent = newPet
bodyGyro.MaxTorque = Vector3.new(math.huge, math.huge, math.huge)
while wait() do
bodyPos.Position = focusPart.Position + focusPart.CFrame.LookVector * z + focusPart.CFrame.RightVector * x
bodyGyro.CFrame = focusPart.CFrame
end
end
Also when you unequip a pet you have to Destroy it from where you store it. In my case I store them in a folder on the player which I call collectionInventory.
local collectionInventory = player:WaitForChild("CollectionInventory")
collectionInventory[petName]:Destroy()
Hope this save anybody else from wasting several hours with research. Even though you will probably learn a lot from those "wasted hours" ;)

Lua - Dynamically generated look up table & values

I’m trying to create a table that is dynamically populated with the on/off status of set of switches I have. The following is where I I’ve got stuck as it always returns nothing/nil? ..
-- retrieved http.request status of 4 binary switches
local P61v = 1
local P62v = 0
local P63v = 1
local P64v = 0
— following table should allow us to look up the status of all associated light by their plug names P61, P62, P63 etc.
local LookupTable = {
P61 = P61v,
P62 = P62v,
P63 = P63v,
P64 = P64v
}
local x = LookupTable[P62]
print(x)
In LookupTable[P62] the expression P62 is evaluated to nil, resulting in LookupTable[nil] which resolves to nil.
What you are looking for is either
LookupTable.P62
-- or --
LookupTable['P62']
which are equivalent ways of expressing the same thing.
I created a script that defines both values, and this is what I ended up with..
local PowerResponse = "P61=0,P62=1,P63=0,P64=0"
local P61, _, P61v, P62, _, P62v, P63, _, P63v, P64, _, P64v = PowerResponse:match("(%w*)(=)(%d),(%w*)(=)(%d),(%w*)(=)(%d),(%w*)(=)(%d)")
local PowerStatusTable = {
P61 = P61v,
P62 = P62v,
P63 = P63v,
P64 = P64v
}
--local x = PowerStatusTable[P62]
for k, v in pairs(PowerStatusTable) do
luup.variable_set("urn:upnp-net:serviceId:IPPower1", k, v,deviceID)
end

Roblox Lua trying to tween part to move back and fourth like a platform

I've been practicing tweening on Lua and I'm struggling to understand why I can't get my platform to move back and fourth between a start and an end platform. First I'll show the code
-- Starting Variables
local TweenService = game:GetService("TweenService")
local group = game.Workspace.MovingPlatform
-- Group Variables
local part = group.Platform
local start = group.Check1
local finish = group.Check2
-- Vectors
local destination = Vector3.new(start.Position.x,start.Position.y, start.Position.z)
-- Platform Tween Info
local info = TweenInfo.new(
1, --Length (seconds)
Enum.EasingStyle.Linear,
Enum.EasingDirection.Out,
-1,--Times To Be Repeated
true,
0 --Delay
)
-- Where the destination is
local Goals = {
Position = Vector3.new(destination)
}
-- Makes it go
local MovePart = TweenService:Create(part, info, Goals)
MovePart:Play()
-- Debugging
local startPosition = Vector3.new(start.Position.x, start.Position.y, start.Position.z)
local endPosition = Vector3.new(finish.Position.x, finish.Position.y, finish.Position.z)
local partPosition = Vector3.new(part.Position.x, part.Position.y, part.Position.z)
while true do
print("Start Position: "..tostring(startPosition))
print("Destination: "..tostring(destination))
print("End Position: "..tostring(endPosition))
print("Platform Position: "..tostring(partPosition))
print("--------------")
wait(3)
end
The platform will move once and then start bugging out and going anywhere and eventually will rest on the floor moving back and fourth but not at the correct location. I've tried debugging to see if the positioning of any of my parts were somehow changing but everything stayed the same. Maybe I'm not logging the positions correctly but nonetheless any hints at what I could be doing wrong?
You might want to try using CFrame instead of Position when moving things.
Also, Part.Position is a Vector3 so there's no point in creating a new Vector3 for a Vector3.
Try something like this:
-- Starting Variables
local TweenService = game:GetService("TweenService")
local group = game.Workspace.MovingPlatform
-- Group Variables
local part = group.Platform
local start = group.Check1
local finish = group.Check2
-- Set the platform part to start at Check1
part.CFrame = start.CFrame
-- Platform Tween Info
local info = TweenInfo.new(
1, --Length (seconds)
Enum.EasingStyle.Linear,
Enum.EasingDirection.Out,
-1,--Times To Be Repeated
true,
0 --Delay
)
-- Where the destination is
local Goals = {
CFrame = finish.CFrame -- We want it to end at the finish part's position
}
-- Makes it go
local MovePart = TweenService:Create(part, info, Goals)
MovePart:Play()

Loading modules from folders

My project structure is following:
--Shooter
----sprites
------background.png
------player.png
------zombie.png
----units
------player.lua
------zombie.lua
----main.lua
----load.lua
----update.lua
----draw.lua
And my main.lua will have the following:
local Bullet = require("units.bullet")
local Player = require("units.player")
local Zombie = require("units.zombie")
require("load")
require("update")
require("draw")
require("functions")
love.window.setTitle("Shooter")
function love.load()
Load()
end
function love.update(dt)
Update(dt)
end
function love.draw()
Draw()
end
For example, bullet.lua:
local Bullet = {}
bulletSprite = love.graphics.newImage('sprites/bullet.png')
function Bullet.create()
local newBullet = {
pos = {},
speed = 10,
sprite = bulletSprite,
direction = 0,
dead = false
}
return setmetatable(newBullet, {__index = Bullet})
end
function Bullet:setPos(x, y)
self.pos.x = x
self.pos.y = y
end
function Bullet:setDirection(angle)
self.direction = angle
end
function Bullet:move(dt)
local distance = self.speed * dt * 60
self.pos.x = self.pos.x + math.cos(self.direction) * distance
self.pos.y = self.pos.y + math.sin(self.direction) * distance
end
function spawnBullet(bullets, player)
local newBullet = Bullet.create()
newBullet:setPos(player.pos.x, player.pos.y)
newBullet.direction = player.angle
table.insert(bullets, newBullet)
end
The problem is that none of the files in units folder will load properly. From the error log I can see that it tries to search for bullet.lua in the root directory and then various love2d and lua libraries.
I have tried various things like require("./units/bullet") or replace / with . but so far, no luck.
Extracting those files from the units folder into root folder will work. Loading images from sprites folder works, however (for example love.graphics.draw(sprites.background, 0, 0)).
Any help?
I found out the problem was that while my main.lua had correct requires, my update file didn't.
Two things come to mind.
Make Sure LUA_PATH is set to your project directory
add return Bullet, return Player and so on... into each module you have created

How to Automatically Add and Rename Objects in Lua?

I am trying to construct a method that automatically adds and renames objects in Lua. I have the add method for adding the object, but I am not sure how to make it so that it renames each object. I'm thinking of adding an if statement, but I don't know how to construct it in a way that it will rename the object each type it loops.
Here is what I have so far:
frogBody = {density = .8, friction = 0.3, bounce = 0.1, radius = 10} -- body Type
local onPlayerSpawnObject = function(object) -- method to spawn object
local layer = map:getTileLayer("Enemies")
local frog = movieclip.newAnim{ "FrogMini.png", "frogMiniRed.png" } -- object that spawns
frog.x = object.x ; frog.y = object.y
frog.myName = "frog"
frog.isHit = false
physics.addBody(frog, frogBody)
end
Thank you for all of your help!
I think that what you mean is that you would like to access the frogs objects from your example distinctively ?
If that is the case you could either assign the return of the add function to a lua table, or directly assign to the table inside your function.
local frogs = {}
frogBody = {density = .8, friction = 0.3, bounce = 0.1, radius = 10} -- body Type
local onPlayerSpawnObject = function(object) -- method to spawn object
local layer = map:getTileLayer("Enemies")
local frog = movieclip.newAnim{ "FrogMini.png", "frogMiniRed.png" } -- object that spawns
frog.x = object.x ; frog.y = object.y
frog.myName = "frog"
frog.isHit = false
physics.addBody(frog, frogBody)
table.insert(frogs, frog)
end
-- To print a distinct frog from the collection, replace 1 by your index
print (frogs[1].myName)

Resources