Target range coordenate

Questions about the LÖVE API, installing LÖVE and other support related questions go here.
Forum rules
Before you make a thread asking for help, read this.
Post Reply
User avatar
maneco2
Prole
Posts: 2
Joined: Sun Feb 19, 2023 12:30 am

Target range coordenate

Post by maneco2 »

have any wayt to get coordenate of distance of the target selected?

Code: Select all

function FollowDistance(target,dist) 
	YQ = target:GetLocation().Y
	YP = self:GetLocation().Y
	XQ = target:GetLocation().X
	XP = self:GetLocation().X
	Mp = -1/((YQ-YP)/(XQ-XP)) 
		if ((-2*XP-2*Mp*Mp*XP)*(-2*XP-2*Mp*Mp*XP) -4*(Mp*Mp+1)*(Mp*Mp*XP*XP + XP*XP-dist*dist) > 0) then
			undersqrt = (-2*XP-2*Mp*Mp*XP)*(-2*XP-2*Mp*Mp*XP) -4*(Mp*Mp+1)*(Mp*Mp*XP*XP + XP*XP-dist*dist);
		else
			undersqrt = (-2*XP-2*Mp*Mp*XP)*(-2*XP-2*Mp*Mp*XP) -4*(Mp*Mp+1)*(Mp*Mp*XP*XP + XP*XP+dist*dist);
		end; 
	XN = (-1*(-2*XP-2*Mp*Mp*XP)+math.sqrt(undersqrt))/(2*(Mp*Mp+1));
	YN = YP + Mp*(XN-XP) 
	MoveToNoWait(XN,YN,self:GetLocation().Z);
end;

repeat
	if (Target() ~= nil) then
		FollowDistance(Target(),100);
	end;
	break;
until false;
Like this example, i'm need follow target in range 100
User avatar
pgimeno
Party member
Posts: 3673
Joined: Sun Oct 18, 2015 2:58 pm

Re: Target range coordenate

Post by pgimeno »

It's hard to understand what is being asked here, but in case you want an enemy to start following a player when it's under a certain range:

Code: Select all

local EnemySpeed = 50
local PlayerSpeed = 70
-- Distance squared - saves a square root when you can use it directly
local function VecDist2(x1, y1, x2, y2)
  return (x2-x1)^2 + (y2-y1)^2
end

-- Distance from a point to another point
local function VecDist(x1, y1, x2, y2)
  return math.sqrt(VecDist2(x1, y1, x2, y2))
end

local PlayerX, PlayerY = 400, 300
local EnemyX, EnemyY = 0, 0

function love.update(dt)
  if VecDist2(EnemyX, EnemyY, PlayerX, PlayerY) < 100^2 then
    -- Make the enemy follow the player
    local EnemyToPlayerDist = VecDist(EnemyX, EnemyY, PlayerX, PlayerY)
    local NormalizedE2PX = (PlayerX - EnemyX) / EnemyToPlayerDist
    local NormalizedE2PY = (PlayerY - EnemyY) / EnemyToPlayerDist
    EnemyX = EnemyX + NormalizedE2PX * dt * EnemySpeed
    EnemyY = EnemyY + NormalizedE2PY * dt * EnemySpeed
  end
  local pressed = love.keyboard.isScancodeDown
  if pressed("left") then PlayerX = PlayerX - dt * PlayerSpeed end
  if pressed("right") then PlayerX = PlayerX + dt * PlayerSpeed end
  if pressed("up") then PlayerY = PlayerY - dt * PlayerSpeed end
  if pressed("down") then PlayerY = PlayerY + dt * PlayerSpeed end
end

function love.draw()
  love.graphics.rectangle("fill", PlayerX - 2, PlayerY - 2, 5, 5)
  love.graphics.setColor(1, 0, 0)
  love.graphics.rectangle("fill", EnemyX - 2, EnemyY - 2, 5, 5)
  love.graphics.setColor(1, 1, 1)
end
Post Reply

Who is online

Users browsing this forum: Bing [Bot] and 9 guests