编辑代码

# 1. 参数初始化
v <- 1.0             # 速度 (m/s)
dt <- 0.005          # 时间步长 (s)

# 2. 初始位置 - 单位正方形
P <- matrix(c(
  0, 0,  # 甲 (A)
  1, 0,  # 乙 (B)
  1, 1,  # 丙 (C)
  0, 1   # 丁 (D)
), nrow = 4, byrow = TRUE)
colnames(P) <- c("x", "y") 

# 3. 数据结构 - 与图片描述一致
robit <- list(
   = P[1, , drop=FALSE],
   = P[2, , drop=FALSE],
   = P[3, , drop=FALSE],
   = P[4, , drop=FALSE]
)

# 定义追逐目标 (A->B, B->C, C->D, D->A)
targets <- c(2, 3, 4, 1)

# 4. 仿真循环
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, ])
    }
}

# 5. 结果可视化
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)
}

# 添加A,B,C,D初始位置标注
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")