import HeightControl from "../functions/robot_control/robot_high_control.js";
import { GameObjects, Math as PhaserMath } from "phaser";
import Effects from "./Effects.js";
//import PathFinder from "../optimizedClasses/PathFinder.js";
phaser matterjs deki
setData ve getData ile
karakter objesinin özellikleri ayarlanacak
böylece npc yi kendi klasına veri taşınacak ve kontrolleri ben gerçekleştireceğim
setData(key: unknown, data?: any): Phaser.Physics.Matter.Sprite
The key to set the value for. Or an object of key value pairs. If an object the data argument is ignored.
this.character.setData("controls",controls);
düşmanın zarar verme katsayısına göre gecikme azalır ve bizi yakalama gücü de artacak
const currentDangerK = defaultDangerK * DangerLevel;
ile bulunur
her mermi yediğinde düşmanımızın kızgınlı artar ve bu oyunu zorlaştırır
son olarak karakter destroyed ise class çalışmaz
tüm hareketler const controls = ... ile olur
*/
import { Math as PhaserMath } from "phaser";
class PathFinder {
constructor(character, my_map, tiles, finder, phaser_timer) {
this.my_map = my_map; // Store the map
this.tiles = tiles;
this.finder = finder; // Store the pathfinding algorithm
this.character = character; // The enemy character
this.phaser_timer = phaser_timer;
code
this.targetPos = null; // Will hold the player's position
}
iterateWay() {
const grid = [];
for (let y = 0; y < this.my_map.height; y++) {
let col = [];
for (let x = 0; x < this.my_map.width; x++) {
col.push(this.getTileID(x, y));
}
grid.push(col);
}
this.finder.setGrid(grid);
}
findWay() {
const tileset = this.my_map.tilesets[0];
const properties = tileset.tileProperties;
const acceptableTiles = [];
for (let i = tileset.firstgid - 1; i < this.tiles.total; i++) {
if (!properties.hasOwnProperty(i)) {
acceptableTiles.push(i + 1);
continue;
}
if (!properties[i].collide) acceptableTiles.push(i + 1);
if (properties[i].cost) this.finder.setTileCost(i + 1, properties[i].cost);
}
this.finder.setAcceptableTiles(acceptableTiles);
}
getTileID(x, y) {
const tile = this.my_map.getTileAt(x, y);
return tile.index;
}
updateCharacterPos(targetCharacter) {
const x = this.character.x;
const y = this.character.y;
const targetX = targetCharacter.x;
const targetY = targetCharacter.y;
this.targetPos = { x: targetX, y: targetY }; // Store target position
this.findPath(x, y, targetX, targetY, "move");
}
findPath(fromX, fromY, toX, toY) {
this.finder.findPath(fromX, fromY, toX, toY, (path) => {
if (path === null) {
console.warn("Path was not found.");
} else {
console.log(path);
this.currentPath = path;
// No need to call moveCharacter()
}
});
this.finder.calculate();
}
moveCharacter(path) {
// Check if there's a path to follow
if (!path || path.length < 2) {
return;
}
// Remove the first point since it's the character's current position
path.shift();
// Define movement speed
const speed = 2; // Adjust as needed
// Create a function to move to the next point
const moveToNextPoint = () => {
if (path.length === 0) {
// Path complete
return;
}
// Get the next waypoint
const nextPoint = path.shift();
const targetX = nextPoint.x * this.my_map.tileWidth;
const targetY = nextPoint.y * this.my_map.tileHeight;
// Calculate the direction vector
const direction = new PhaserMath.Vector2(targetX - this.character.x, targetY - this.character.y);
const distance = direction.length();
// Normalize the direction vector
direction.normalize();
// Set the velocity
this.character.setVelocity(direction.x * speed, direction.y * speed);
// Wait until the character reaches the waypoint
const checkArrival = () => {
const dx = this.character.x - targetX;
const dy = this.character.y - targetY;
const distanceToTarget = Math.sqrt(dx * dx + dy * dy);
if (distanceToTarget < 5) { // Threshold, adjust as needed
// Stop the character
this.character.setVelocity(0, 0);
// Move to the next point
moveToNextPoint();
} else {
// Continue checking
this.phaser_timer.delayedCall(50, checkArrival, [], this);
}
};
checkArrival();
};
// Start moving
moveToNextPoint();
}
// **New Method**
setViaController() {
let controls = this.character.getData('controls');
const angerRange = this.character.getData('angerRange');
const dangerLevel = this.character.getData('danger');
// Ensure controls is an object (in case it hasn't been set)
if (!controls) {
controls = {
jump: false,
left: false,
right: false,
shoot: false
};
this.character.setData('controls', controls);
}
// Use the path to decide movement
if (this.currentPath && this.currentPath.length > 1) {
const nextPoint = this.currentPath[1]; // The next point to move towards
const targetX = nextPoint.x * this.my_map.tileWidth;
const targetY = nextPoint.y * this.my_map.tileHeight;
const dx = targetX - this.character.x;
const dy = targetY - this.character.y;
const threshold = 5; // Threshold to prevent jittery movement
// Horizontal movement
if (Math.abs(dx) > threshold) {
if (dx > 0) {
controls.right = true;
} else {
controls.left = true;
}
}
// Vertical movement (jumping)
if (dy < -threshold && this.character.body.blocked.down) {
controls.jump = true;
}
// If close to the next point, remove it from the path
if (Math.abs(dx) <= threshold && Math.abs(dy) <= threshold) {
this.currentPath.shift(); // Remove the current point
}
}
// Shooting decision based on danger level
if (dangerLevel >= angerRange.max - 1) {
controls.shoot = true;
}
// Update the controls in the character's data
this.character.setData('controls', controls);
}
}
export default PathFinder;
Merhaba! Kodunuz üzerinde daha fazla geliştirme yapmak ve düşmanın davranışını "anger" (kızgınlık) seviyesine göre ayarlamak istiyorsunuz. Ayrıca left, right ve jump gibi hareketleri daha modüler hale getirmek istiyorsunuz.
Size yardımcı olmak için bazı öneriler ve kod modifikasyonları sunacağım.
1. Hareket Kontrollerini Modüler Hale Getirmek
Öncelikle, left, right, jump gibi hareketleri ayrı fonksiyonlar haline getirmek iyi bir fikir. Böylece kodunuz daha okunaklı ve yönetilebilir olur.
Var olan kodunuzda bu hareketleri zaten ayrı fonksiyonlar olarak tanımlamışsınız:
Bu fonksiyonları kullanarak düşmanın hareketini kontrol edebiliriz.
2. "Anger" Seviyesini Kullanma
Düşmanın "anger" seviyesini kullanarak davranışını dinamik olarak ayarlamak istiyorsunuz. Örneğin, düşman hasar aldıkça kızgınlığı artacak ve daha agresif davranacak.
Bunu yapmak için anger seviyesini düşmanın setData ve getData fonksiyonlarıyla saklayabiliriz.
Anger Seviyesini Başlatma
Düşman oluşturulduğunda başlangıç "anger" seviyesini ayarlayın:
Düşmanın "anger" seviyesine göre davranışını değiştirebiliriz. Örneğin, "anger" seviyesine bağlı olarak daha hızlı hareket edebilir veya daha sık saldırabilir.
javascript
loop() {
if (this.alive) {
// Mevcut kodunuz...
const angerLevel = this.enemy.getData('anger');
const angerFactor = angerLevel / this.enemy.getData('angerRange').max;
// Hareket hızı
const speed = 2 + angerFactor * 3; // Temel hız 2, maksimum ekstra hız 3
// Saldırı sıklığı
const attackDelay = 1000 - angerFactor * 500; // Temel gecikme 1000ms, minimum 500ms
// Hareket
if (this.targetEnemiesDistance < this.width / 2) {
if (playerX < this.enemy.x) {
this.left(speed);
} else if (playerX > this.enemy.x) {
this.right(speed);
}
} else {
this.Idle();
}
// Saldırı için zamanlayıcıyı ayarlayın
if (!this.attackTimer) {
this.attackTimer = this.scene.time.addEvent({
delay: attackDelay,
callback: () => {
if (this.alive) {
this.attack();
}
},
loop: true
});
} else {
// Zamanlayıcının gecikmesini güncelleyin
this.attackTimer.delay = attackDelay;
}
}
}
3. Kontrolleri Kullanarak Hareketi Yönetme
Düşmanın hareketini ve eylemlerini controls nesnesi üzerinden yönetmek, daha tutarlı ve genişletilebilir bir yaklaşım sağlar.
applyControls(controls, angerFactor) {
if (controls.left) {
this.left(2 + angerFactor * 2); // Hız, anger seviyesine göre artar
}
if (controls.right) {
this.right(2 + angerFactor * 2);
}
if (controls.jump) {
this.jump(-5); // Sabit bir zıplama gücü
}
if (controls.shoot) {
this.attack();
}
if (!controls.left && !controls.right && !controls.jump && !controls.shoot) {
this.Idle();
}
}
4. Düşman Yok Edildiğinde Sınıfın Çalışmasını Durdurma
Düşman yok edildiğinde, sınıfın çalışmasını durdurmak için alive bayrağını kullanabilirsiniz. Mevcut kodunuzda bunu zaten yapıyorsunuz.
Ancak, zamanlayıcıları veya olayları temizlemek iyi bir fikir olabilir:
javascript
death() {
if (this.alive) {
this.alive = false;
// Zamanlayıcıları temizleyin
if (this.attackTimer) {
this.attackTimer.remove();
}
// Diğer temizleme işlemleri
this.healthBar.clear();
this.healthBar.destroy();
this.enemy.destroy();
this.scene.battle_mechas.splice(this.scene.battle_mechas.indexOf(this), 1);
}
}
5. Engelleri Aşmak İçin Pathfinder Kullanımı
Düşmanın engelleri aşabilmesi için PathFinder sınıfını kullanabilirsiniz. Bu sınıfı zaten sağlamışsınız. Düşmanın hedefe ulaşmak için yolu bulmasını ve hareket etmesini sağlar.
Döngü içinde pathfinder'ı güncelleyebilir ve düşmanın hareketini kontroller aracılığıyla ayarlayabilirsiniz:
javascript
loop() {
if (this.alive) {
// Mevcut kodunuz...
// Pathfinder'ı güncelle
this.pathFinder.updateCharacterPos(this.scene.player);
this.pathFinder.setViaController();
// Kontrolleri al ve uygula
const controls = this.enemy.getData('controls');
const angerLevel = this.enemy.getData('anger');
const angerFactor = angerLevel / this.enemy.getData('angerRange').max;
this.applyControls(controls, angerFactor);
}
}
Sonuç
Bu değişikliklerle, düşmanınızın davranışını "anger" seviyesine göre dinamik olarak değiştirebilir, hareket ve eylemleri modüler hale getirebilir ve kontroller aracılığıyla daha esnek bir sistem oluşturabilirsiniz.
Umarım bu öneriler ve kod değişiklikleri size yardımcı olur. Eğer başka sorunuz varsa veya daha fazla yardım isterseniz, lütfen sormaktan çekinmeyin!