設定兩個坐標點,一個初始點,一個終點,隨著時間的推移這個物體在這兩點之間回圈勻速移動,這樣的代碼怎么實作? 怎么判定這個物體到達終點并且原路回傳? 期間任意時刻物體的坐標都需要能夠表示出來。
哪位大佬能寫個代碼嗎?
uj5u.com熱心網友回復:
#include <iostream>
#include <ctime>
#include <vector>
#include <cmath>
using namespace std;
typedef struct MOVE {
vector<float> start;
vector<float> end;
vector<float> location;
vector<float> direction;
float speedPerMs;
long time = 0;
long endTime = 0;
long timeGap = 0;
MOVE(vector<float> start, vector<float> end, float speedPerMs, long time): start(start), end(end), location(start), speedPerMs(speedPerMs), time(time) {
auto length = (float)sqrt(pow(end[0] - start[0], 2) + pow(end[1] - start[1], 2));
direction = {(end[0] - start[0]) / length, (end[1] - start[1]) / length};
timeGap = length / speedPerMs;
endTime = time + timeGap;
}
} moveInfo;
void move(moveInfo& info, long time) {
int dt = time - info.time;
info.location[0] += info.direction[0] * dt * info.speedPerMs;
info.location[1] += info.direction[1] * dt * info.speedPerMs;
info.time = time;
if (time >= info.endTime) {
info.location = info.end;
info.end = info.start;
info.start = info.location;
info.direction = {-info.direction[0], -info.direction[1]};
info.endTime += info.timeGap;
}
}
int main() {
struct timeval time{};
mingw_gettimeofday(&time, nullptr);
moveInfo info({0, 0}, {3, 5}, 0.01, time.tv_sec * 1000 + time.tv_usec / 1000);
for (int i = 0; i < 3000; ++i) {
mingw_gettimeofday(&time, nullptr);
move(info, time.tv_sec * 1000 + time.tv_usec / 1000);
cout<<info.location[0]<<" "<<info.location[1]<<endl;
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/12596.html
標籤:模式及實現
