Jump to content

Create your own FPS Character Controller in LUA - Part 2

tipforeveryone

1,906 views

II. Implement advanced actions

Previous tutorial guided you to create your own FPS Character Controller with basic actions: Move, Look.

This tutorial will help you add some advanced actions like Jump, Run, Crouch, and Lean

*Note: Below steps will use code from previous tutorial (CharacterController.lua)

1. Jump / Run / Crouch

Firstly, build obtacle with space under it to test crouching, the space height shoud be at least 120cm (leadwerks editor will show you this height in other viewports) You can not crouch and pass space under 120cm, this was hardcoded

crouchheightest_zpsjy2bkvjg.jpg

crouchheightest2_zpshwme61xh.jpg

Next, modify the code.

Add new variables under --Character movement variables comment. Note that putting script variables at the top of script will allow you to modify character stat easier and faster than finding variables deep inside script's functions

--Character movement variables
Script.playerSpeed = 2 --higer = faster
Script.playerRunSpeedMultipier = 2 --if this variable < 1, you can make slower movement
Script.playerJumpForce = 7 --This defines how high you can jump
Add new funtion to smooth movement of character components
function Script:SmoothPosition(position,entity,rate)
local smoothX = Math:Curve(position.x,entity:GetPosition().x,rate)
local smoothY = Math:Curve(position.y,entity:GetPosition().y,rate)
local smoothZ = Math:Curve(position.z,entity:GetPosition().z,rate)
entity:SetPosition(smoothX,smoothY,smoothZ)
end
Replace code in Character_Movement() function by this code
function Script:Character_Movement()
	local playerSpeed, playerJumpForce, playerCrouch

	--Press Space bar to Jump
	if window:KeyHit(Key.Space) then playerJumpForce = self.playerJumpForce else playerJumpForce = 0 end

	--Hold Ctrl key to Crouch
	if window:KeyDown(Key.ControlKey) then
		playerCrouch = true
	else
		if self.playerHeadBlocked then playerCrouch = true else playerCrouch = false end
	end

	--Hold Shift key + AWSD to Run
	if window:KeyDown(Key.Shift) then
		playerSpeed = self.playerSpeed * self.playerRunSpeedMultipier
	else
		playerSpeed = self.playerSpeed
	end

	local playerMove = ((window:KeyDown(Key.W) and 1 or 0) - (window:KeyDown(Key.S) and 1 or 0)) * playerSpeed
	local playerStrafe = ((window:KeyDown(Key.D)and 1 or 0) - (window:KeyDown(Key.A) and 1 or 0)) * playerSpeed
	--Using local playerSpeed varialbe instead of self.playerSpeed in the old code
	local playerTurn = self.playerNeck:GetRotation(true).y

	self.playerBase:SetInput(playerTurn,playerMove,playerStrafe,playerJumpForce,playerCrouch)
end
Replace code in Bind_Character_Components_Together() function too
function Script:Bind_Character_Components_Together()
	--Must use this reposition process because playerBase is not playerNeck's parent, they are indipendent.

	local basePos = self.playerBase:GetPosition(true)
	local height

	if window:KeyDown(Key.ControlKey) then
		height = basePos.y + (self.playerHeight - self.neckLength) / 2
		--You can adjust this variable to get desired crouch height for playerNeck (and playerEyes too)
	else
		if self.playerHeadBlocked then
			height = basePos.y + (self.playerHeight - self.neckLength) / 2
		else
			height = basePos.y + self.playerHeight - self.neckLength
		end
	end

	self:SmoothPosition(Vec3(basePos.x,height,basePos.z),self.playerNeck,10)
end
Add a new function to script, this will keep player crouching if something block above character when release Ctrl key, prevent from being pushed around by obtacle when standing.
function Script:Check_Head_Block()
	--We can use a raycast to check if something block character head when crouching
	local pickInfo = PickInfo()
	local point1 = self.playerNeck:GetPosition(true)
	local point2 = self.playerBase:GetPosition(true) + Vec3(0,self.playerHeight,0)
	if world:Pick(point1,point2,pickInfo,0.3,true) then
		self.playerHeadBlocked = true
	else
		self.playerHeadBlocked = false
	end
end
Update Script:UpdateWorld() function with new Check_Head_Block() function
function Script:UpdateWorld()
	self:Bind_Character_Components_Together()
	self:Check_Head_Block()
	self:Character_Look()
	self:Character_Movement()
end
Now, you can crouch under obtacle, release Ctrl Key and you are still crouching. Continue moving for auto standing.

2. Leaning

In Character_Movement() function, add this code after Crouching code

--Hold Q/E to lean Left/Right
local leanDistance = 0.025 --leanDistance should be < 0.025 or camera will pass through wall when you get too close
if window:KeyDown(Key.Q) then self.playerEyes:Move(-leanDistance,-0.01,0) end
if window:KeyDown(Key.E) then self.playerEyes:Move(leanDistance,-0.01,0) end
And add this line at the bottom of Bind_Character_Components_Together() function
self:SmoothPosition(Vec3(0,self.neckLength,0),self.playerEyes,10)
You can lean now, so smooth.

Final script file was attached to this entry. You can apply it to a pivot point (PlayerControl).

CharacterController.lua



5 Comments


Recommended Comments

I have recently come back to this blog to go through the code again to make a character controller and I seem to be getting an issue with the player camera. I have attached my script to a CSG box and when I move the camera rotates but doesn't follow the box, it's as if the camera's position is fixed but I can still rotate it. Not to sure where I have gone wrong as all I have done is copy and paste the code.

Share this comment


Link to comment

If you press the jump button while in the air you can still jump, you can fix this by using raycasts to find if the player is grounded or not.

Share this comment


Link to comment

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Add a comment...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

  • Blog Entries

    • By Josh in Josh's Dev Blog 2
      For finer control over what 2D elements appear on what camera, I have implemented a system of "Sprite Layers". Here's how it works:
      A sprite layer is created in a world. Sprites are created in a layer. Layers are attached to a camera (in the same world). The reason the sprite layer is linked to the world is because the render tweening operates on a per-world basis, and it works with the sprite system just like the entity system. In fact, the rendering thread uses the same RenderNode class for both.
      I have basic GUI functionality working now. A GUI can be created directly on a window and use the OS drawing commands, or it can be created on a sprite layer and rendered with 3D graphics. The first method is how I plan to make the new editor user interface, while the second is quite flexible. The most common usage will be to create a sprite layer, attach it to the main camera, and add a GUI to appear in-game. However, you can just as easily attach a sprite layer to a camera that has a texture render target, and make the GUI appear in-game on a panel in 3D. Because of these different usages, you must manually insert events like mouse movements into the GUI in order for it to process them:
      while true do local event = GetEvent() if event.id == EVENT_NONE then break end if event.id == EVENT_MOUSE_DOWN or event.id == EVENT_MOUSE_MOVE or event.id == EVENT_MOUSE_UP or event.id == EVENT_KEY_DOWN or event.id == EVENT_KEY_UP then gui:ProcessEvent(event) end end You could also input your own events from the mouse position to create interactive surfaces, like in games like DOOM and Soma. Or you can render the GUI to a texture and interact with it by feeding in input from VR controllers.

      Because the new 2D drawing system uses persistent objects instead of drawing commands the code to display elements has changed quite a lot. Here is my current button script. I implemented a system of abstract GUI "rectangles" the script can create and modify. If the GUI is attached to a sprite layer these get translated into sprites, and if it is attached directly to a window they get translated into system drawing commands. Note that the AddTextRect doesn't even allow you to access the widget text directly because the widget text is stored in a wstring, which supports Unicode characters but is not supported by Lua.
      --Default values widget.pushed=false widget.hovered=false widget.textindent=4 widget.checkboxsize=14 widget.checkboxindent=5 widget.radius=3 widget.textcolor = Vec4(1,1,1,1) widget.bordercolor = Vec4(0,0,0,0) widget.hoverbordercolor = Vec4(51/255,151/255,1) widget.backgroundcolor = Vec4(0.2,0.2,0.2,1) function widget:MouseEnter(x,y) self.hovered = true self:Redraw() end function widget:MouseLeave(x,y) self.hovered = false self:Redraw() end function widget:MouseDown(button,x,y) if button == MOUSE_LEFT then self.pushed=true self:Redraw() end end function widget:MouseUp(button,x,y) if button == MOUSE_LEFT then self.pushed = false if self.hovered then EmitEvent(EVENT_WIDGET_ACTION,self) end self:Redraw() end end function widget:OK() EmitEvent(EVENT_WIDGET_ACTION,self) end function widget:KeyDown(keycode) if keycode == KEY_ENTER then EmitEvent(EVENT_WIDGET_ACTION,self) self:Redraw() end end function widget:Start() --Background self:AddRect(self.position, self.size, self.backgroundcolor, false, self.radius) --Border if self.hovered == true then self:AddRect(self.position, self.size, self.hoverbordercolor, true, self.radius) else self:AddRect(self.position, self.size, self.bordercolor, true, self.radius) end --Text if self.pushed == true then self:AddTextRect(self.position + iVec2(1,1), self.size, self.textcolor, TEXT_CENTER + TEXT_MIDDLE) else self:AddTextRect(self.position, self.size, self.textcolor, TEXT_CENTER + TEXT_MIDDLE) end end function widget:Draw() --Update position and size self.primitives[1].position = self.position self.primitives[1].size = self.size self.primitives[2].position = self.position self.primitives[2].size = self.size self.primitives[3].size = self.size --Update the border color based on the current hover state if self.hovered == true then self.primitives[2].color = self.hoverbordercolor else self.primitives[2].color = self.bordercolor end --Offset the text when button is pressed if self.pushed == true then self.primitives[3].position = self.position + iVec2(1,1) else self.primitives[3].position = self.position end end This is arguably harder to use than the Leadwerks 4 system, but it gives you advanced capabilities and better performance that the previous design did not allow.
    • By Josh in Josh's Dev Blog 4
      I have been working on 2D rendering off and on since October. Why am I putting so much effort into something that was fairly simple in Leadwerks 4? I have been designing a system in anticipation of some features I want to see in the GUI, namely VR support and in-game 3D user interfaces. These are both accomplished with 2D drawing performed on a texture. Our system of sprite layers, cameras, and sprites was necessary in order to provide enough control to accomplish this.
      I now have 2D drawing to a texture working, this time as an official supported feature. In Leadwerks 4, some draw-to-texture features were supported, but it was through undocumented commands due to the complex design of shared resources between OpenGL contexts. Vulkan does not have this problem because everything, including contexts (or rather, the VK equivalent) is bound to an abstract VkInstance object.

      Here is the Lua code that makes this program:
      --Get the primary display local displaylist = ListDisplays() local display = displaylist[1]; if display == nil then DebugError("Primary display not found.") end local displayscale = display:GetScale() --Create a window local window = CreateWindow(display, "2D Drawing to Texture", 0, 0, math.min(1280 * displayscale.x, display.size.x), math.min(720 * displayscale.y, display.size.y), WINDOW_TITLEBAR) --Create a rendering framebuffer local framebuffer = CreateFramebuffer(window); --Create a world local world = CreateWorld() --Create second camera local texcam = CreateCamera(world) --Create a camera local camera = CreateCamera(world) camera:Turn(45,-45,0) camera:Move(0,0,-2) camera:SetClearColor(0,0,1,1) --Create a texture buffer local texbuffer = CreateTextureBuffer(512,512,1,true) texcam:SetRenderTarget(texbuffer) --Create scene local box = CreateBox(world) --Create render-to-texture material local material = CreateMaterial() local tex = texbuffer:GetColorBuffer() material:SetTexture(tex, TEXTURE_BASE) box:SetMaterial(material) --Create a light local light = CreateLight(world,LIGHT_DIRECTIONAL) light:SetRotation(55,-55,0) light:SetColor(2,2,2,1) --Create a sprite layer. This can be shared across different cameras for control over which cameras display the 2D elements local layer = CreateSpriteLayer(world) texcam:AddSpriteLayer(layer) texcam:SetPosition(0,1000,0)--put the camera really far away --Load a sprite to display local sprite = LoadSprite(layer, "Materials/Sprites/23.svg", 0, 0.5) sprite:MidHandle(true,true) sprite:SetPosition(texbuffer.size.x * 0.5, texbuffer.size.y * 0.5) --Load font local font = LoadFont("Fonts/arial.ttf", 0) --Text shadow local textshadow = CreateText(layer, font, "Hello!", 36 * displayscale.y, TEXT_LEFT, 1) textshadow:SetColor(0,0,0,1) textshadow:SetPosition(50,30) textshadow:SetRotation(90) --Create text text = textshadow:Instantiate(layer) text:SetColor(1,1,1,1) text:SetPosition(52,32) text:SetRotation(90) --Main loop while window:Closed() == false do sprite:SetRotation(CurrentTime() / 30) world:Update() world:Render(framebuffer) end I have also added a GetTexCoords() command to the PickInfo structure. This will calculate the tangent and bitangent for the picked triangle and then calculate the UV coordinate at the picked position. It is necessary to calculate the non-normalized tangent and bitangent to get the texture coordinate, because the values that are stored in the vertex array are normalized and do not include the length of the vectors.
      local pick = camera:Pick(framebuffer, mousepos.x, mousepos.y, 0, true, 0) if pick ~= nil then local texcoords = pick:GetTexCoords() Print(texcoords) end Maybe I will make this into a Mesh method like GetPolygonTexCoord(), which would work just as well but could potentially be useful for other things. I have not decided yet.
      Now that we have 2D drawing to a texture, and the ability to calculate texture coordinates at a position on a mesh, the next step will be to set up a GUI displayed on a 3D surface, and to send input events to the GUI based on the user interactions in 3D space. The texture could be applied to a computer panel, like many of the interfaces in the newer DOOM games, or it could be used as a panel floating in the air that can be interacted with VR controllers.
    • By Josh in Josh's Dev Blog 0
      Putting all the pieces together, I was able to create a GUI with a sprite layer, attach it to a camera with a texture buffer render target, and render the GUI onto a texture applied to a 3D surface. Then I used the picked UV coords to convert to mouse coordinates and send user events to the GUI. Here is the result:

      This can be used for GUIs rendered onto surfaces in your game, or for a user interface that can be interacted with in VR. This example will be included in the next beta update.
×
×
  • Create New...