WebSim2D - Advanced 2D Robotics Simulator
// Advanced robot control code function exploreEnvironment() { if (goal) { // Calculate angle to goal const dx = goal.x - robotX; const dy = goal.y - robotY; const angleToGoal = Math.atan2(dy, dx); // Calculate difference between current angle and angle to goal let angleDiff = angleToGoal - robotAngle; // Normalize angle difference to [-PI, PI] while (angleDiff > Math.PI) angleDiff -= 2 * Math.PI; while (angleDiff < -Math.PI) angleDiff += 2 * Math.PI; if (Math.abs(angleDiff) > 0.1) { // Turn towards goal robot.setVelocity(0, angleDiff > 0 ? 0.5 : -0.5); } else if (!robot.detectObstacle()) { // Move towards goal robot.setVelocity(0.5, 0); } else { // Obstacle avoidance robot.setVelocity(0, -0.5); } } else { // No goal, just explore if (!robot.detectObstacle()) { robot.setVelocity(0.5, 0); } else { robot.setVelocity(0, -0.5); } } } // Start exploration for 10 seconds robot.run(exploreEnvironment, 10000);
Run Simulation
Add Obstacle
Add Goal
Clear World