04-11-2024, 04:59 PM
(This post was last modified: 04-11-2024, 05:09 PM by Marcus.
Edit Reason: removed pretty possible division by 0 :D
)
(04-11-2024, 01:51 PM)aliensoldier Wrote: A question, if I have two objects and one is the player who can move with the keys and the other is the enemy who is stationary in one place on the screen.
The question would be how can I make it so that when the player is close to the enemy he starts chasing the player and if the player moves away the enemy stops chasing him and returns to the starting position.
Here is a small example:
Code:
set window "Chasing enemy", 640, 480, false
set redraw off
' Player.
visible player = [x: 100, y: 100, w: 32, h: 32]
' Move with arrow keys.
player.Update = function()
if keydown(KEY_LEFT) this.x = this.x - 4
if keydown(KEY_RIGHT) this.x = this.x + 4
if keydown(KEY_UP) this.y = this.y - 4
if keydown(KEY_DOWN) this.y = this.y + 4
endfunc
player.Draw = function()
set color 255, 255, 0
draw rect this.x, this.y, this.w, this.h, true
endfunc
' Enemy.
enemy = [baseX: 400, baseY: 100, x: 400, y: 100, w: 32, h: 32, chasing: false, home: true, speed: 2]
enemy.Update = function()
' Calculate distance to player.
dx = player.x - this.x
dy = player.y - this.y
d = sqr(dx*dx + dy*dy)
' Toggle chasing based on distance.
if this.chasing
' Stop chasing if distance is larger than 150.
if d > 150
this.chasing = false
this.home = false
endif
else
' Start chasing if distance is less than 100.
if d < 100
this.chasing = true
endif
endif
' Chasing?
if this.chasing
' Move towards player.
if d > 0
k = this.speed/d
this.x = this.x + dx*k
this.y = this.y + dy*k
endif
' Not chasing, return to base position if not already there.
elseif not this.home
' Calculate distance to base position.
dx = this.baseX - this.x
dy = this.baseY - this.y
d = sqr(dx*dx + dy*dy)
' Home?
if d < this.speed
this.x = this.baseX
this.y = this.baseY
this.home = true
' Move towards home.
else
k = this.speed/d
this.x = this.x + dx*k
this.y = this.y + dy*k
endif
endif
endfunc
enemy.Draw = function()
' Draw base position just for testing.
set color 64, 64, 64
draw rect this.baseX, this.baseY, this.w, this.h
' Different color when chasing.
if this.chasing set color 255, 0, 0
else set color 128, 128, 128
draw rect this.x, this.y, this.w, this.h, true
endfunc
while not keydown(KEY_ESCAPE, true)
player.Update()
enemy.Update()
set color 0, 0, 0
cls
player.Draw()
enemy.Draw()
redraw
fwait 60
wend
Hope it helps! If there's something you don't understand, please ask