Jump to content

havenphillip

Members
  • Posts

    550
  • Joined

  • Last visited

Posts posted by havenphillip

  1. Ah man now I'm getting "attempt to index nil value" error when I add a crawler to the scene. What's that about? Do I need to do some kind of CountChildren() cycle?

            for k,v in pairs (self.modelTable) do
                for i = 0, self.modelTable[k]:CountSurfaces()-1, 1 do
                    surface = self.modelTable[k]:GetSurface(i)  <- giving me an error on this line
                    mat = surface:GetMaterial()
                    mat:SetShader(shader)
                    shader:SetVec4("ex_color",self.color)
                    mat:SetColor(self.color)
                    self.modelTable[k] = nil
                end
            end

  2. Ah thanks! This seems to be working so far:

            for k,v in pairs (self.modelTable) do
                for i = 0, self.modelTable[k]:CountSurfaces()-1, 1 do
                    surface = self.modelTable[k]:GetSurface(i)
                    mat = surface:GetMaterial()
                    mat:SetShader(shader)
                    shader:SetVec4("ex_color",self.color)
                    mat:SetColor(self.color)
                    self.modelTable[k] = nil
                end
            end

  3. I keep getting this error. How can I fix this? I'm trying to grab everything in the scene and change the color of it with a bounding box. It works fine so long as I don't put a model in the scene that has a model childed to it. The "generator_withbutton.mdl" is an example. When I put that in the scene I get the error.

     

            for k,v in pairs (self.modelTable) do
                surface = self.modelTable[k]:GetSurface(0)
                mat = surface:GetMaterial()
                mat:SetShader(shader)
                shader:SetVec4("ex_color",self.color)
                mat:SetColor(self.color)
                self.modelTable[k] = nil
            end

  4. Ah ok I see. But now it's blue, even though the color is set to 1,1,1. How do I fix that?:

        surface = self.entity:GetSurface(0)
        mat = surface:GetMaterial()
        mat:SetColor(1,1,1)
        shader = Shader:Load("Gloss/wet_rock.shader");
        mat:SetShader(shader)
        self.entity:SetMaterial(mat)
        shader:SetFloat("puddlesize", self.puddleSize)
        shader:SetFloat("puddlefade", self.puddleFade)
        shader:SetFloat("intensity" , self.intensity)
        mat:Release()

     

    funky rock.png

  5. Actually I see GetSurface() but I'm getting this funky looking rock which ought to look more like the second picture.

    Here's my code here so far:

    function Script:Start()

        --mat = Material:Load("Gloss/wet_rock.mat")
        mat = Material:Create()
        surface = self.entity:GetSurface(0)
        surface:SetMaterial(material)
        shader = Shader:Load("Gloss/wet_rock.shader");
        mat:SetShader(shader)
        self.entity:SetMaterial(mat)
        shader:SetFloat("puddlesize", self.puddleSize)
        shader:SetFloat("puddlefade", self.puddleFade)
        shader:SetFloat("intensity" , self.intensity)
        mat:Release()

    end


     

    funky rock.png

    funky rock2.png

  6. In the above timer script you have to use  "defaultFont = context:GetFont()" at the start of your PostRender() function, then you set the font to the font you want with " context:SetFont(self.font) ", then you "DrawText(...)" and after you have to set it back to the default font with " context:SetFont(defaultFont)." I'm guessing you have other scripts that use the DrawText() function? You have to use "defaultFont = context:GetFont()" and " context:SetFont(defaultFont) " in every script that uses "DrawText(...)".

    Basic Font script:
    This shouldn't change your other fonts because you're resetting the font back to the default here:

    Script.myFont = "" --path "Font"
    Script.color = Vec4(1,1,1,1) --color "Color"
    Script.size = 12

    function Script:Start()

        self.myFont= Font:Load(self.myFont,self.size)
    end

    function Script:PostRender(context)

        defaultFont = context:GetFont() --at start of every postrender function
        
        context:SetBlendMode(1)
        context:SetColor(self.color)
        context:SetFont(self.myFont) -- changed to your font
        context:DrawText("My Text" ,20,20,100,100)
        
        context:SetFont(defaultFont) -- change font back to default at end of every postrender function anywhere "SetFont()" and "DrawText()" are used
    end

  7. The clock isn't restarting because the script is calling Time:GetCurrent(). When you change maps the application doesn't restart, so it's counting the application running time. So what you need is Time:GetSpeed(). That's probably a better way to do a timer anyway.

    Script.font = "" -- path "Font" -- use TrueType font file
    Script.pos = Vec2(0,30) -- Vec2 "Position"
    Script.size = 15 -- float "Size"
    Script.color = Vec4(1,1,0,1) -- color "Color"
    Script.offset = 20 -- int "Offset" -- make larger if numbers get cut off
    Script.countSpeed = 0.05 -- float "Count Speed" (smaller is slower)
    Script.time = 0

    function Script:Start()
        self.font = Font:Load(self.font,self.size)
        if self.font == nil then
            Debug:Error("Select a font")
        end
    end

    function Script:UpdateWorld()
        self.counter = Time:GetSpeed() * self.countSpeed
        self.time = self.time + self.counter
    end

    function Script:PostRender(context)

        defaultFont = context:GetFont()

        r = self.size + self.offset
        w = self.pos.x + window:GetWidth()/2 - self.offset
        h = self.pos.y

        context:SetBlendMode(1)
        context:SetColor(self.color)
        context:SetFont(self.font)
        context:DrawText(Math:Round(self.time),w,h,r,r,Text.VCenter+Text.Center)

        context:SetFont(defaultFont)
    end

    Not sure what you mean by the font sizes. You want to change the font in the gui?
     

  8. I would try something like:

    function Script:UpdateWorld()
    If window:KeyHit(Key.A) then

      changemapname=self.mapname

    end


    Here's the triggerChangeMap script.

    --[[
    This script will act as a trigger to change the current map.
    Place this at the end of your map to make the player progress
    to the next level.
    ]]--

    Script.mapname=""--string "Map Name"

    function Script:Start()
        self.enabled=true
    end

    function Script:Collision(entity, position, normal, speed)
        changemapname=self.mapname
    end

    function Script:Enable()--in
        if self.enabled==false then
            self.enabled=true
            self:CallOutputs("Enable")
        end
    end

    function Script:Disable()--in
        if self.enabled then
            self.enabled=false
            self:CallOutputs("Disable")
        end
    end

     

  9. One thing about this I've noticed is the flashlight doesn't evenly light the ground in 360 degrees. If I change "nmat" in the vertex shader from:

        //Sky
        mat3 nmat = mat3(camerainversematrix); //inverse sky on model stays in place
        ex_normal = normalize(nmat * vertex_normal);    
        ex_tangent = normalize(nmat * vertex_tangent);
        ex_binormal = normalize(nmat * vertex_binormal);

    ...to this, the flashlight works correctly but the sky reflection doesn't.

        //Flashlight
        //mat3 nmat = mat3(entitymatrix); //flashlight works 360
        //ex_normal = normalize(nmat * vertex_normal);    
        //ex_tangent = normalize(nmat * vertex_tangent);
        //ex_binormal = normalize(nmat * vertex_binormal);

    I tried a few things including using an "if" statement but haven't been able to solve this. If anyone's already figured this out I'd like a solution. It's not too much of a big deal. It just irks me.

  10. They're kind of stretching long on the x-axis so you can go in the shader and find this line (around line 49):
    vec2 spec_texcoords0 = ex_texcoords0/(vec2(puddlesize));
    ...and change it to this:
    vec2 spec_texcoords0 = ex_texcoords0/(vec2(puddlesize/2,puddlesize));

    That seems to have squared them up.

  11. Bepuddled terrain effect. I was able to put this together based on an old Shadmar shader I began fiddling with, but it's different enough that I didn't feel the need to credit him so I did it here.

    *credits Shadmar*

    Make a box and attach the waterterrain.lua script to it. Then drag the player into the "Player" slot of the script so it can access the camera. That's it. (Also don't forget to have a skybox set)

    Some settings considerations:
    It looks better on darker terrains so I set the diffuse color to about half, put the specular all the way up and set roughness to 0.0 in the Material Editor. Terrains tend to look darker when wet anyway.

    Diffuse texture is set to uncompressed with mipmaps because it's so large.

    Textures should be set up as shown below.

     

     

    Water Terrain.zip

     

    bepuddled.png

    setting.png

    clickdrag.png

    • Like 4
  12. Ok it looks like I had to put this line :

        Context:SetCurrent(self.context)


    ...in the PostRender() function. It was initially in the UpdateWorld() function. That seems to have resolved that.

    But now it's still happening to this crawler. He sort of "smudges" as I turn. What's causing this?

     

    funky water problem.jpg

  13. I've been messing around with this Shadmar shader and is there any way to keep my PostRender() items from showing up in the water model? Do I need to clear a buffer somewhere or what? It seems to have something to do with the refraction texture in the shader but I don't even know how I would start to approach this. What's happening here?

    funky water problem.jpg

  14. Yeah, man. That's a little quirk in the system that I guess Josh never got around to straightening out.

    Go to Scripts folder, and find "Main.lua". Open that and look for this:

        if gamemenu:Hidden() then
            
            --Update the app timing
            Time:Update()

            --Update the world
            world:Update()
            
        end

        --Render the world
        world:Render()


    ...then right before "world:Render()" add this line:

        gamemenu.gui:GetBase():Redraw()



     

    fixbug.jpg

  15. Yeah put a pivot in the scene and attach the script to the pivot. The pivot can be anywhere on the map. It doesn't matter because the PostRender() stuff will show up in the same place on screen regardless.

     

    pivottoscene.png

    scripttopivot.png

  16. Script.font = "" -- path "Font" -- use TrueType font file
    Script.pos = Vec2(0,30) -- Vec2 "Position"
    Script.size = 15 -- float "Size"
    Script.color = Vec4(1,1,0,1) -- color "Color"
    Script.offset = 20 -- int "Offset" -- make larger if numbers get cut off

    function Script:Start()
        self.font = Font:Load(self.font,self.size)
        if self.font == nil then
            Debug:Error("Select a font")
        end
    end

    function Script:PostRender(context)

        defaultFont = context:GetFont()

        r = self.size + self.offset
        w = self.pos.x + window:GetWidth()/2 - self.offset
        h = self.pos.y

        --time factor
        time = Time:GetCurrent()/1000
        context:SetBlendMode(1)
        context:SetColor(self.color)
        context:SetFont(self.font)
        context:DrawText(Math:Round(time),w,h,r,r,Text.VCenter+Text.Center)
        context:SetFont(defaultFont)
    end




  17. You might want to post the script where this error is occurring so people can look through it for themselves. It's difficult to see what the number comparing with nil is:

    attemp to compare number with nil Line 8

    If you're using my pickup script from above I might have changed something and that might be a different error.

    I would troubleshoot it by making sure that:

    1. Maybe in your player script, under the Start() function you want to add: self.entity:SetKeyValue("type","player")

    2. Your gun script has these at the top somewhere:
          Script.clipsize=6--int "Clip size"
          Script.ammo=200--int "Ammunition"
          Script.maxammo = 200 -- int "Max Ammo"

    3. Your gun script has this in the Start() function:

        self.clipammo=self.clipsize

        self.ammo = self.ammo - self.clipammo
        self.muzzle = self.entity:FindChild("muzzle")


    This is the vwep gun script I use with that ammo pickup script. I don't remember if I changed anything:

    --import "Scripts/AnimationManager.lua"

    Script.index=1--int "Weapon slot"
    Script.offset=Vec3(0,0,0)--Vec3 "Offset"
    Script.rotation=Vec3(0,0,0)--Vec3 "Rotation"
    Script.clipsize=6--int "Clip size"
    Script.ammo=200--int "Ammunition"
    Script.maxammo = 200 -- int "Max Ammo"
    Script.maxswayamplitude=0.01
    Script.amplitude=0
    Script.swayspeed=0
    Script.timeunits=0
    Script.smoothedposition=Vec3(0)
    Script.smoothedrotation=Vec3(0)
    Script.verticalbob=0
    Script.jumpoffset=0
    Script.bulletspeed=200--float "Bullet speed"
    Script.landoffset=0
    Script.pellets=1--int "Pellets"
    Script.scatter=0.01--float "Scatter"
    Script.firetime=0
    Script.refirerate=100--int "Refire rate"
    Script.bulletrange=1000
    Script.muzzleflashscale=0.2--float "Flash size"
    Script.bulletforce=500--float "Force"
    Script.bulletdamage=10--int "Damage"
    Script.automatic=true--bool "Automatic"
    Script.dryfiresoundfile=""--path "Dry fire" "Wav File (*wav):wav|Sound"
    Script.fire1soundfile=""--path "Fire sound 1" "Wav File (*wav):wav|Sound"
    Script.fire2soundfile=""--path "Fire sound 2" "Wav File (*wav):wav|Sound"
    Script.fire3soundfile=""--path "Fire sound 3" "Wav File (*wav):wav|Sound"
    Script.pumpsoundfile=""--path "Pump sound" "Wav File (*wav):wav|Sound"
    Script.ricochet1soundfile=Sound:Load("Sound/Ricochet/bullet_impact_dirt_01.wav")
    Script.ricochet2soundfile=Sound:Load("Sound/Ricochet/bullet_impact_dirt_02.wav")
    Script.ricochet3soundfile=Sound:Load("Sound/Ricochet/bullet_impact_dirt_03.wav")
    Script.reloadsoundfile=""--path "Reload sound" "Wav File (*wav):wav|Sound"
    Script.reloadspeed=0.05--float "Reload speed"
    Script.firespeed=0.05--float "Fire speed"
    Script.tracer = Sprite:Create()
    Script.tracer:Hide()
    Script.currentaction=nil

    function Script:Start()
        if self.started then return end
        self.started=true

        self.entity:SetPickMode(0,true)

        self.entity:SetAnimationFrame(0,1,"fire")

        self.entity:Hide()
        
        self.bullets = {}
        
        self.entity:SetShadowMode(0)
        self.entity:SetOcclusionCullingMode(false)
        
        self.tracer:SetViewMode(6)--Rotate around z axis
        self.tracer:SetSize(0.1,2)
        local mtl = Material:Load("Materials/Effects/tracer.mat")
        if mtl then
            self.tracer:SetMaterial(mtl)
            mtl:Release()
        end

        self.currentaction=nil
        self.clipammo=self.clipsize

        self.ammo = self.ammo - self.clipammo
        self.muzzle = self.entity:FindChild("muzzle")
        
        self.sound={}
        if self.sound.dryfiresoundfile~="" then self.sound.dryfire=Sound:Load(self.dryfiresoundfile) end
        self.sound.fire={}
        if self.pumpsoundfile~="" then self.sound.pump=Sound:Load(self.pumpsoundfile) end
        if self.fire1soundfile~="" then self.sound.fire[1]=Sound:Load(self.fire1soundfile) end
        if self.fire2soundfile~="" then self.sound.fire[2]=Sound:Load(self.fire2soundfile) end
        if self.fire3soundfile~="" then self.sound.fire[3]=Sound:Load(self.fire3soundfile) end
        if self.reloadsoundfile~="" then
            self.sound.reload=Sound:Load(self.reloadsoundfile)
        end
        self.sound.ricochet={}
        self.sound.ricochet[1]=Sound:Load("Sound/Ricochet/bullet_impact_dirt_01.wav")
        self.sound.ricochet[2]=Sound:Load("Sound/Ricochet/bullet_impact_dirt_02.wav")
        self.sound.ricochet[3]=Sound:Load("Sound/Ricochet/bullet_impact_dirt_03.wav")
        
        self.entity:SetPickMode(0)
        
        self.muzzleflash = Sprite:Create()
        self.muzzleflash:SetSize(self.muzzleflashscale,self.muzzleflashscale)
        self.muzzleflash:SetCollisionType(0)
        local material = Material:Load("Materials/Effects/muzzleflash.mat")
        self.muzzleflash:SetMaterial(material)
        self.muzzlelight = PointLight:Create()
        self.muzzlelight:SetColor(1,0.75,0)
        self.muzzlelight:SetRange(4)
        self.muzzleflash:SetShadowMode(0)
        local tag = self.entity:FindChild("muzzle")
        self.muzzlelight:SetParent(tag)
        self.muzzlelight:SetPosition(0,0,0)
        self.muzzlelight:Hide()
        self.muzzleflash:SetParent(self.muzzlelight,false)
        --self.animationmanager = AnimationManager:Create(self.entity)
        self.originalposition = self.entity:GetPosition()
        self.originalrotation = self.entity:GetRotation()
        self.emitter={}
        
        --Debris emitter - This will throw chunks off of walls and make it look like they are breaking
        self.emitter[0]=Emitter:Create()
        self.emitter[0]:SetCollisionType(Collision.Prop)--Enables particle bouncing
        self.emitter[0]:SetMaterial("Materials/Effects/default.mat")
        self.emitter[0]:SetEmissionVolume(0.05,0.05,0.05)    
        self.emitter[0]:SetColor(0.1,0.1,0.1,1)
        self.emitter[0]:SetVelocity(1.5,1.5,1.5,1)
        self.emitter[0]:SetParticleCount(5)
        self.emitter[0]:SetReleaseQuantity(5)
        self.emitter[0]:SetMaxScale(0.3)
        self.emitter[0]:SetDuration(1500)
        self.emitter[0]:SetAcceleration(0,-12,0)
        self.emitter[0]:Hide()
        
        --Smoke emitter - This will provide a soft dust effect around bullet impacts
        self.emitter[1]=Emitter:Create()
        self.emitter[1]:SetColor(1,1,1,0.25)
        self.emitter[1]:SetMaterial("Materials/Effects/smoke.mat")
        self.emitter[1]:SetEmissionVolume(0.1,0.1,0.1)
        self.emitter[1]:SetVelocity(0.3,0.3,0.3,1)
        self.emitter[1]:SetParticleCount(3)
        self.emitter[1]:SetReleaseQuantity(3)
        self.emitter[1]:SetMaxScale(4)
        self.emitter[1]:SetDuration(2500)
        self.emitter[1]:AddScaleControlPoint(0,0.5)
        self.emitter[1]:AddScaleControlPoint(1,1)
        self.emitter[1]:SetRotationSpeed(10)
        self.emitter[1]:Hide()
        
        --Blood emitter - This will provide a visual cue when an enemy is shot
        self.emitter[2]=self.emitter[1]:Instance()
        self.emitter[2] = tolua.cast(self.emitter[2],"Emitter")
        self.emitter[2]:SetMaterial("Materials/Effects/bloodspatter.mat")
        self.emitter[2]:SetColor(1,1,1,0.25)
        self.emitter[2]:SetParticleCount(3)
        self.emitter[2]:SetReleaseQuantity(3)
        self.emitter[2]:SetDuration(200)
        self.emitter[2]:SetEmissionVolume(0,0,0)
        self.emitter[2]:SetMaxScale(1)
        self.emitter[2]:SetRotationSpeed(10)
        self.emitter[2]:AddScaleControlPoint(0,0)
        self.emitter[2]:AddScaleControlPoint(1,1)
        self.emitter[2]:SetVelocity(0,0,0,0)
        self.emitter[2]:SetVelocity(0,0,0,1)
        self.emitter[2]:Hide()
        
        --[[if self.autogive then
            local player,n
            for n,player in ipairs(players) do
                player:AddWeapon(self,self.index)
            end
        end]]--

        self.entity:Hide()
    end

    function Script:Holster()
        if self.entity:FindAnimationSequence("holster")>-1 then
            --self.animationmanager:SetAnimationSequence("holster",self.reloadspeed,0,1)--,self,self.EndHolster,25)        
            self.entity:PlayAnimation("holster",self.reloadspeed,0,1)
        end
    end

    function Script:Unholster()
        if self.entity:FindAnimationSequence("unholster")>-1 then
            --self.animationmanager:SetAnimationSequence("unholster",self.reloadspeed,0,1)
            self.entity:PlayAnimation("unholster",self.reloadspeed,0,1)    
            self.currentaction="unholster"
        end
    end

    function Script:Hide()
        self.entity:Hide()
        self.muzzlelight:Hide()
    end

    function Script:FindScriptedParent(entity,func)
        while entity~=nil do
            if entity.script then
                if type(entity.script[func])=="function" then
                    --if entity.script.enabled~=false then
                        return entity
                    --else
                    --    return nil
                    --end
                end
            end
            entity = entity:GetParent()
        end
        return nil
    end

    function Script:BeginJump()
        self.jumpoffset = -180
    end

    function Script:BeginLand()
        self.landoffset = -180
    end

    function Script:FinalizeReload()
        self.currentaction=nil
        if self.cancelreload then
            self.cancelreload=false
        end
    end

    function Script:EndReload()
        if self.entity:FindAnimationSequence("ReloadLoop")>-1 then
            if self.ammo>0 and self.clipammo<self.clipsize and (self.reloadedshells==0 or self.cancelreload==false) then
                if self.sound.reload~=nil then
                    self.sound.reload:Play()
                end
                --self.animationmanager:SetAnimationSequence("ReloadLoop",self.reloadspeed,300,1,self,self.EndReload)
                self.entity:PlayAnimation("ReloadLoop",self.reloadspeed,300,1,"EndReload")
                self.clipammo = self.clipammo + 1
                self.ammo = self.ammo - 1
                self.reloadedshells = self.reloadedshells + 1
            else
                --self.animationmanager:SetAnimationSequence("ReloadEnd",self.reloadspeed,300,1,self,self.FinalizeReload)
                self.entity:PlayAnimation("ReloadEnd",self.reloadspeed,300,1,"FinalizeReload")
            end
        else
            self.currentaction=nil
            local rounds = self.clipsize - self.clipammo
            rounds = math.min(self.ammo,rounds)
            self.ammo = self.ammo - rounds
            self.clipammo = self.clipammo + rounds
        end
    end

    function Script:CanReload()
        if self.currentaction==nil then return true else return false end
    end

    function Script:Reload()
        if self.currentaction==nil then
            self.cancelreload=false
            if self.clipammo<self.clipsize and self.ammo>0 and self.currentaction==nil then
                self.currentaction="reload"
                self.reloadedshells=0
                if self.entity:FindAnimationSequence("Reload")>-1 then
                    --self.animationmanager:SetAnimationSequence("Reload",self.reloadspeed,300,1,self,self.EndReload)
                    self.entity:PlayAnimation("Reload",self.reloadspeed,300,1,"EndReload")
                    self.reloadstarttime=Time:GetCurrent()
                    if self.sound.reload~=nil then self.sound.reload:Play() end
                elseif self.entity:FindAnimationSequence("ReloadStart")>-1 then
                    --self.animationmanager:SetAnimationSequence("ReloadStart",self.reloadspeed,300,1,self,self.EndReload)
                    self.entity:PlayAnimation("ReloadStart",self.reloadspeed,300,1,"EndReload")
                end                
            end
        end
    end

    function Script:FinalizeFire()
        self.currentaction=nil
    end

    function Script:EndFire()
        if self.entity:FindAnimationSequence("Pump")>-1 then
            --self.animationmanager:SetAnimationSequence("Pump",0.03,300,1,self,self.FinalizeFire)
            self.entity:PlayAnimation("Pump",0.03,300,1,"FinalizeFire")
            if self.sound.pump~=nil then self.sound.pump:Play() end
        else
            self.currentaction=nil
        end
    end

    function Script:UpdateWorld()
        local bullet,n,dist
        local pickinfo=PickInfo()
        local firstbullet=true
        local travel
        
        for n,bullet in ipairs(self.bullets) do
            
            --Check how far the bullet has travelled
            dist = (bullet.position-bullet.origin):Length()
            if dist>self.bulletrange then
                table.remove(self.bullets,n)
                bullet.sprite:Release()
                bullet=nil
            end
            
            if bullet~=nil then
                travel = bullet.velocity/60.0*Time:GetSpeed()
                if self.entity.world:Pick(bullet.position,bullet.position+travel,pickinfo,0,true,Collision.Projectile) then
                    
                    --Find first parent with the Hurt() function
                    local enemy = self:FindScriptedParent(pickinfo.entity,"Hurt")
                    
                    --local sph = Model:Sphere()
                    --sph:SetPosition(pickinfo.position)
                    
                    --Bullet mark decal
                    local mtl
                    local scale = 0.1
                    if enemy~=nil then
                        mtl = Material:Load("Materials/Decals/wound.mat")
                        scale = 0.1
                    else
                        if pickinfo.surface~=nil then
                            local pickedmaterial = pickinfo.surface:GetMaterial()
                            if pickedmaterial~=nil then
                                rendermode = pickedmaterial:GetDecalMode()
                             end
                        end
                        mtl = Material:Load("Materials/Decals/bulletmark.mat")
                    end
                    local decal = Decal:Create(mtl)
                    decal:AlignToVector(pickinfo.normal,2)
                    decal:Turn(0,0,Math:Random(0,360))
                    decal:SetScript("Scripts/Objects/Effects/BulletMark.lua")
                    if mtl~=nil then mtl:Release() end
                    decal:SetPosition(pickinfo.position)
                    decal:SetParent(pickinfo.entity)
                    
                    --Apply global scaling
                    local mat = decal:GetMatrix()
                    mat[0] = mat[0]:Normalize() * scale
                    mat[1] = mat[1]:Normalize() * scale
                    mat[2] = mat[2]:Normalize() * scale    
                    decal:SetMatrix(mat)
                    
                    table.remove(self.bullets,n)
                    
                    bullet.sprite:Release()
                    
                    if enemy~=nil then
                        if enemy.script.health>0 then
                            enemy.script:Hurt(self.bulletdamage,self.player)
                            --kills counter
                            --if enemy.script.health <=0 then
                              --  self.player.kills = self.player.kills + 1
                           -- end
                        end
                        
                        --Blood emitter
                        --[[e = self.emitter[2]:Instance()
                        e = tolua.cast(e,"Emitter")
                        e:Show()
                        e:SetLoopMode(false,true)
                        e:SetPosition(pickinfo.position+pickinfo.normal*0.1)
                        e:SetVelocity(0,0,0)]]--
                        
                    else
                        
                        --Add a temporary particle emitter for bullet effects
                        local e
                        
                        e = self.emitter[0]:Instance()
                        e = tolua.cast(e,"Emitter")
                        e:Show()
                        e:SetLoopMode(false,true)
                        e:SetPosition(pickinfo.position)
                        local v=3
                        e:SetVelocity(pickinfo.normal.x*v,pickinfo.normal.y*v,pickinfo.normal.z*v,0)
                        
                        --Smoke emitter
                        e = self.emitter[1]:Instance()
                        e = tolua.cast(e,"Emitter")
                        e:Show()
                        e:SetLoopMode(false,true)
                        e:SetPosition(pickinfo.position+pickinfo.normal*0.1)
                        local v=0.2
                        e:SetVelocity(pickinfo.normal.x*v,pickinfo.normal.y*v,pickinfo.normal.z*v,0)
                        
                        --Play bullet impact noise
                        e:EmitSound(self.sound.ricochet[math.random(#self.sound.ricochet)],30)
                        
                        if pickinfo.entity~=nil then
                            
                            --Add impulse to the hit object
                            if pickinfo.entity:GetMass()>0 then
                                --local force = pickinfo.normal*-1*self.bulletforce
                                local dir = bullet.velocity:Normalize()
                                local force = dir * self.bulletforce * math.max(0,-pickinfo.normal:Dot(dir))
                                --force = force * math.max(0,-pickinfo.normal:Dot(d))--multiply by dot product of velocity and collided normal, to weaken glancing blows
                                pickinfo.entity:AddPointForce(force,pickinfo.position)
                            end
                            
                            --Extract a partial surface from the hit surface and make a bullet mark
                            --To be added later
                            --if pickinfo.surface~=nil then
                            --    local aabb = AABB(pickinfo.position-radius,pickinfo.position+radius)    
                            --    local surf = pickinfo.surface:Extract(aabb)
                            --end
                        end
                    end
                    
                else
                    bullet.position = bullet.position+travel
                    bullet.sprite:SetPosition(bullet.position - bullet.velocity:Normalize()*1)
                    if bullet.sprite:Hidden() then
                        dist = (bullet.position-bullet.origin):Length()
                        if dist>bullet.sprite:GetSize().y then
                            bullet.sprite:Show()
                        end
                    end
                end
            end
            firstbullet = false
        end
    end

    function Script:Fire()
        if self.player.weaponlowerangle==0 then
            local currenttime=Time:GetCurrent()
            if self.lastfiretime==nil then self.lastfiretime=0 end
            if currenttime-self.lastfiretime>self.refirerate then
                if self.currentaction==nil then            
                    self.lastfiretime = currenttime
                    if self.clipammo==0 then
                        if self.sound.dryfire then
                            if self.suspenddryfire~=true then
                                self.sound.dryfire:Play()
                            end
                        end
                    else
                        self.currentaction="fire"
                        if #self.sound.fire>0 then
                            self.sound.fire[math.random(#self.sound.fire)]:Play()                    
                        end
                        self.clipammo = self.clipammo - 1
                        self.firetime = Time:GetCurrent()
                        self.muzzlelight:Point(self.player.camera,1)
                        self.muzzlelight:Show()
                        self.muzzleflash:SetAngle(math.random(0,360))
                        --self.animationmanager:SetAnimationSequence("Fire",self.firespeed,300,1,self,self.EndFire)
                        self.entity:PlayAnimation("Fire",self.firespeed,300,1,"EndFire")
                        
                        --Spawn bullet
                        local n
                        for n=1,self.pellets do
                            local d = Transform:Normal(0,0,1,self.player.camera,nil)
                            d = d + Vec3(math.random(-1,1),math.random(-1,1),math.random(-1,1)) * self.scatter
                            d = d:Normalize()
                            local p
                            if self.muzzle then
                                p=self.muzzle:GetPosition(true)
                                self:SpawnBullet(p,d*self.bulletspeed)
                            else
                                System:Print("Warning: Muzzle entity not found.")
                            end                                                
                        end
                    end
                else
                    self.cancelreload=true
                end
            end
        end
    end

    --Creates a bullet
    function Script:SpawnBullet(position,velocity)
        local bullet = {}
        bullet.sprite = tolua.cast(self.tracer:Instance(),"Sprite")
        bullet.sprite:SetPosition(position)
        bullet.sprite:AlignToVector(velocity)
        bullet.sprite:Hide()
        bullet.position = position
        bullet.origin = Vec3(position.x,position.y,position.z)
        bullet.velocity = velocity
        table.insert(self.bullets,bullet)
    end

    function Script:Draw()
        
        local t = Time:GetCurrent()

        if self.muzzlelight:Hidden()==false then
            if t-self.firetime>50 then
                self.muzzlelight:Hide()
            end
        end
        
        local jumpbob = 0
        
        if self.jumpoffset<0 then
            jumpbob = (Math:Sin(self.jumpoffset))*0.01
            self.jumpoffset = self.jumpoffset + 8*Time:GetSpeed()
        end
        
        if self.landoffset<0 then
            jumpbob = jumpbob + (Math:Sin(self.landoffset))*0.01
            self.landoffset = self.landoffset + 10*Time:GetSpeed()
        end

        --Animate the weapon
        local bob = 0;
        local speed = math.max(0.1,self.player.entity:GetVelocity():xz():Length())
        if self.player.entity:GetAirborne() then speed = 0.1 end
        self.swayspeed = Math:Curve(speed,self.swayspeed,20)
        self.swayspeed = math.max(0.5,self.swayspeed)
        self.amplitude = math.max(2,Math:Curve(speed,self.amplitude,20))
        self.timeunits = self.timeunits + self.swayspeed*4*Time:GetSpeed()
        local sway = math.sin(self.timeunits/120.0) * self.amplitude * self.maxswayamplitude
        bob = (1-math.cos(self.timeunits/60.0)) * self.maxswayamplitude * 0.1 * self.amplitude
        local campos = self.player.camera:GetPosition(true)
        
        self.smoothedposition.x = campos.x
        self.smoothedposition.y = Math:Curve(campos.y,self.smoothedposition.y,2)
        self.smoothedposition.z = campos.z
        self.entity:SetRotation(self.rotation)    
        self.entity:SetPosition(sway*self.entity.scale.x,bob+jumpbob,0)
        self.entity:Translate(self.offset,false)
        
        --self.animationmanager:Update()
    end

    function Script:Release()
        if self.emitter~=nil then
            self.emitter[0]:Release()
            self.emitter[1]:Release()
            self.emitter[2]:Release()
            self.emitter=nil
        end
        if self.sound~=nil then
            ReleaseTableObjects(self.sound)
            self.sound=nil
        end
    end

    function Script:Cleanup()
        self.tracer:Release()
    end

     


     

    • Thanks 1
  18. This one works for me. You might need to post your whole script with your question isn't working so they can look through it for the error:

    Script.ammoamount = 6 --float "Ammo Amount Per"
    Script.ammotype= 2 --int "Ammo Type"
    Script.maxammo="" --int "Max Ammo"
    Script.ammo = 5
    Script.removeBodyTime = 20 --int "Despawn Time"
    Script.removeBodyTimer = 0
    Script.useOnce = true --bool "Use Once"
    Script.enabled = true --bool "Enabled"
    Script.floatup1 = false
    Script.counter= 0


    function Script:Start()

        --Load a sound
        self.sound = Sound:Load("Sound/Interaction/pickupammo.wav")

        self.enabled = true
        self.entity:SetMass(0)
        local os = self.entity:GetPosition()
        self.entity:SetPosition(os.x,os.y+1,os.z)
    end

    function Script:floatUp(amount)
        local a1 = self.entity:GetPosition()
        local b1 = amount/20
        self.entity:SetPosition(a1.x,a1.y + b1,a1.z)
    end

    function Script:UpdatePhysics()
        local window = Window:GetCurrent()

        if window:KeyHit(Key.O) then self:ChangeFloat() end
        local lastpos = self.entity:GetPosition()
        if self.enabled==true then
        
            if self.lastchangetime==nil then self.lastchangetime=0 end
            local t = Time:GetCurrent()
            local floatamount
                if self.floatup1==true then floatamount= 0.03 else floatamount = -0.03 end
                self:floatUp(floatamount)
                self.counter = self.counter +1
                if self.counter >= 100 then
                    self:ChangeFloat()
                    self.counter=0
                end
                self.lastchangetime = t
        end
    end

    function Script:ChangeFloat()
             if (self.floatup1 == false) then
                self.floatup1=true
            else
                self.floatup1=false
            end
    end

    function Script:UpdateWorld()
        self.entity:Turn(0,Time:GetSpeed(),0,true)

        self.removeBodyTimer = self.removeBodyTimer + (Time:GetSpeed()/100)
            if (self.removeBodyTimer > self.removeBodyTime) then
                self:IsHidden()
            end
    end

    function Script:Collision(entity, position, normal, speed)
        if entity:GetKeyValue("type")=="player" then
            for a = 0, 10 do
                if entity.script.weapons[a]~=nil then
                    if entity.script.weapons[a].index == self.ammotype then
                        if entity.script.weapons[a].ammo + entity.script.weapons[a].clipammo < entity.script.weapons[a].maxammo then
                            entity.script.weapons[a].ammo = entity.script.weapons[a].ammo + self.ammoamount
                        
                            --Make sure the sound exists and play it
                            if self.sound then
                                self.sound:Play()
                            end
        
                            if entity.script.weapons[a].ammo + entity.script.weapons[a].clipammo > entity.script.weapons[a].maxammo then
                                entity.script.weapons[a].ammo = entity.script.weapons[a].maxammo - entity.script.weapons[a].clipammo
                            end

                            if     self.useOnce then
                                self:IsHidden()
                            end
                        end
                    end
                end
            end
        end
    end

    function Script:IsHidden()
        self.entity:Hide()
        if self.entity:Hide() then
            self.entity:Release()
        end
    end

×
×
  • Create New...