【发布时间】:2017-06-26 20:14:15
【问题描述】:
我正在开发画布迷你游戏,我想构建一个函数来计算将你的船从 A 点移动到 B 点的成本。
我需要两件事:
- 发货前的总成本
- 每个移动滴答的成本(服务器循环滴答)
每次移动船(每次服务器循环滴答声)都会收取费用,因此总数必须与服务器为到达那里所做的所有滴答声的总和相匹配。
我有一个简单的服务器循环来移动船:
setInterval(function() {
ship.move();
}, 10);
现在是简化的船代码:
var rad = (p1, p2) => Math.atan2(p2.y - p1.y, p2.x - p1.x),
distance = (p1, p2) => Math.sqrt( (p1.x - p2.x) * (p1.x - p2.x) + (p1.y - p2.y) * (p1.y - p2.y) );
var ship = function() {
this.x; // current ship x
this.y; // current ship y
this.destination; // destination object
this.total_distance; // total distance before dispatch
this.remaining_distance; // remaining distance before arrival
this.speed = 0.5; // ship speed modifier
this.set_travel = function(target) {
this.destination = target;
this.total_distance = distance( { x: this.x, y: this.y }, { x: this.destination.x, y: this.destination.y } );
};
this.move = function() {
this.remaining_distance = distance( { x: this.x, y: this.y }, { x: this.destination.x, y: this.destination.y } );
var _rad = rad( { x: this.x, y: this.y }, { x: this.destination.x, y: this.destination.y } );
this.x += Math.cos(rad) * this.speed;
this.y += Math.sin(rad) * this.speed;
};
};
现在我们可以引入燃料成本并像这样添加到上面的代码中:
var ship = function() {
...
this.total_fuel_cost; // total fuel cost that player will consume during entire travel
this.set_travel = function(target) {
...
this.total_fuel_cost = ?
};
this.move = function() {
...
player.fuel -= ? // fuel cost every tick that must match total after arrival
};
};
也许有人可以帮助解决这个问题。也许假设每 1 距离花费 x 燃料可能是一个好方法,但我不知道是否可以这样做。
----- 编辑
当船被创建时,它以这种方式被实例化:
objects.push(new ship())
正如我在我的问题中解释的那样,如果总数不够,拒绝飞行是不可接受的,只要有燃料,船就必须走
【问题讨论】:
标签: javascript math