Page 1 of 1

How to teleport?

Posted: Sun Oct 30, 2022 5:46 am
by Brah
I want to have the player in my game be able to teleport, but after I added physics to my game I can't teleport anymore. How do I make both the rectangle and the physics shape teleport?

Code: Select all

player = {}

function player:load()
    self.x = 300
    self.y = 300
    self.width = 32
    self.height = 64
    self.radius = 16
    
    self.health = 1000
    self.energy = 1000
    self.max_energy = 1000

    self.xVel = 0
    self.yVel = 0
    self.speed = 30000
    self.body = love.physics.newBody(world, self.x, self.y, "dynamic")
    self.body:setFixedRotation(true)
    --self.body:setMass(10)
    self.shape = love.physics.newCircleShape(self.radius)
    self.fixture = love.physics.newFixture(self.body, self.shape) --density?
end

function player:update(dt)
    --Physics Sync
    self.x, self.y = self.body:getPosition()
    self.body:setLinearVelocity(self.xVel, self.yVel)

    --Movement
    if love.keyboard.isDown("d") then
        self.body:applyForce(self.speed, 0) 
    elseif love.keyboard.isDown("a") then
        self.body:applyForce(-self.speed, 0) 
    end
    if love.keyboard.isDown("w") then
        self.body:applyForce(0, -self.speed)
    elseif love.keyboard.isDown("s") then
        self.body:applyForce(0, self.speed)
    end
end

function player:draw()
    --Placeholder Player
    love.graphics.setColor(0,0,1,0.5)
    love.graphics.rectangle("fill", self.x - self.width / 2, self.y - self.height / 2, self.width, self.height)
end

function player:mousepressed(x, y, b)

end

function player:keypressed(k)
    if k == "space" then
        self.x = mouse_x
        self.y = mouse_y
        print("teleport")
    end
end

Re: How to teleport?

Posted: Sun Oct 30, 2022 6:10 am
by Andlac028
Try self.body:setPosition(newx, newy)

Re: How to teleport?

Posted: Sun Oct 30, 2022 10:52 am
by Brah
Thanks for the idea! This fixed it

Code: Select all

function player:keypressed(k)
    if k == "space" then
        self.body:setPosition(mouse_x, mouse_y)
        print("teleport")
    end
end