Love2d Player Movement
Archived 2 months ago
O
ocro
Junior Dev!
I am trying to make a simple player controller where when i press shift the player moves towards the cursor
It works but i don't know how to fix the jitter it does
The code is in 2 files:
`main.lua`
```lua
require("player")
function love.load()
player = Player.new(0, 0)
player.speed = 100
mouseX, mouseY = love.mouse.getPosition();
end
function love.update(dt)
mouseX, mouseY = love.mouse.getPosition();
local key_up = love.keyboard.isDown("lshift")
local key_space = love.keyboard.isDown("space")
if key_up then
Player:move(dt, {["x"] = mouseX, ["y"] = mouseY})
end
end
function love.draw()
love.graphics.rectangle("fill", player.x, player.y, 5, 5)
end
```
`player.lua`
```lua
Player = {}
Player.setmetatable = Player
function Player.new(x, y, speed, stop_radius)
Player.x = x
Player.y = y
Player.speed = speed or 100
-- Player.dash_speed = dash_speed or 100
Player.stop_radius = 20
return Player
end
function Player:move(dt, cursor)
-- Check whether the player is at the stop radius or not
dx = cursor.x - player.x
dy = cursor.y - player.y
distance = math.sqrt(dx^2 + dy^2)
-- Only move if the player is outside the stop radius
if distance >= Player.stop_radius then
local angle = math.atan2(dy, dx)
local angle = angle * (180/math.pi)
Player.x = Player.speed * math.cos(angle) * dt + Player.x
Player.y = Player.speed * math.sin(angle) * dt + Player.y
end
end
return Player
```
Ong idk how to fix ts
