v <- 1.0
dt <- 0.005
P <- matrix(c(
0, 0,
1, 0,
1, 1,
0, 1
), nrow = 4, byrow = TRUE)
colnames(P) <- c("x", "y")
robit <- list(
甲 = P[1, , drop=FALSE],
乙 = P[2, , drop=FALSE],
丙 = P[3, , drop=FALSE],
丁 = P[4, , drop=FALSE]
)
targets <- c(2, 3, 4, 1)
while (sqrt(sum((P[1,] - P[2,])^2)) > 0.01) {
P_old <- P
for (i in 1:4) {
pos_current <- P_old[i, ]
pos_target <- P_old[targets[i], ]
direction_vector <- pos_target - pos_current
distance <- sqrt(sum(direction_vector^2))
velocity_vector <- v * (direction_vector / distance)
P[i, ] <- pos_current + velocity_vector * dt
robit[[i]] <- rbind(robit[[i]], P[i, ])
}
}
plot(NA, xlim=c(0, 1), ylim=c(0, 1), xlab="X", ylab="Y",
main="四人追逐轨迹 (单位正方形)", asp=1)
grid()
colors <- c("#d62728", "#2ca02c", "#1f77b4", "#ff7f0e")
labels <- c("甲", "乙", "丙", "丁")
for(i in 1:4){
lines(robit[[i]], type='l', col=colors[i], lwd=2)
}
text(0, 0, labels="A", adj=c(1.5, 1.5))
text(1, 0, labels="B", adj=c(-0.5, 1.5))
text(1, 1, labels="C", adj=c(-0.5, -0.5))
text(0, 1, labels="D", adj=c(1.5, -0.5))
legend("bottomleft", legend=labels, col=colors, lty=1, lwd=2, bg="white")