game-js/src/Game/NPC/NPCController/NPCController.js
2024-04-19 16:05:51 +03:00

96 lines
2.6 KiB
JavaScript

import { GameObject } from "../../GameObject/GameObject";
import { PointInt2D } from "../../Utils/Math.utils";
import { NavigationPath, PathFinder } from "../../Utils/PathFinding.utils";
import { NPCProto } from "../NPCProto/NPCProto";
/**
* NPCController defines NPC behavior. Many NPC can have same NPCController for the same behavior.
*/
export class NPCController extends GameObject
{
/**
* NPC controlled by this controller
* @type NPCProto
*/
controlledNPC = null;
/**
* @type Array<PointInt2D>
*/
navigationPathQueue = new Array();
navigationInProgress = false;
navigationFollowMidPoint = false;
navigationCallback = ()=>{};
constructor(tickAble = true)
{
super(tickAble);
}
/**
* moves NPC to position
* @param {PointInt2D} position
* @param {Function} callback
*/
moveTo(position, callback)
{
let pf = new PathFinder();
let nPath = pf.search(new PointInt2D(this.controlledNPC.worldPosition.getX(), this.controlledNPC.worldPosition.getY()), position);
console.log(nPath);
if(nPath.error)
{
callback("failed");
return;
}
else if (nPath.result.path.length < 2)
{
callback("success");
return;
}
for (let i = nPath.result.path.length-1; i > 0; i--) {
this.navigationPathQueue.push(nPath.result.path[i]);
}
this.navigationCallback = callback;
this.navigationInProgress = true;
}
/**
*
* @param {NavigationPath} pathToFollow
* @param {Function} callback
*/
_moveByPath(pathToFollow, callback)
{
}
tick(ticker)
{
if(this.navigationInProgress)
{
if(!this.navigationFollowMidPoint)
{
let target = this.navigationPathQueue.pop();
if(!target)
{
this.navigationInProgress = false;
this.navigationCallback("success");
}
else
{
this.controlledNPC.worldPosition = target;
this.navigationFollowMidPoint = true;
}
}
else
{
if(
Math.abs(this.controlledNPC.drawObject.x - this.controlledNPC.worldPosition.getX()) < 0.5 &&
Math.abs(this.controlledNPC.drawObject.y - this.controlledNPC.worldPosition.getY()) < 0.5
)
{
this.navigationFollowMidPoint = false;
}
}
}
}
};