Task
Design a code that will initialize a random point on the map, after which the tank will begin smooth movement with a turn towards this point.
Implementation attempt
rotation – Global variable responsible for the angle of rotation in
radians about the y-axis from -PI to +PI.
global_position –
Global variable storing the global coordinates of the tank.velocity – Tank movement vector, in this case it is always directed
up and simply rotated using the rotate() method.
func _find_random_point():
var _random_point = Vector2(randf_range(0, 500), randf_range(0, 500))
# Sets the coordinates of a random point on the map
return _random_point
var target_position = _find_random_point() # Назначает координаты в переменную
func _rad_to_rad(rad):
if rad > PI:
return PI - rad
elif rad < -PI:
return rad - PI
else:
return rad
func _abs_rad(rad):
if rad < 0:
return PI + (PI - abs(rad))
else:
return rad
func _abs_rotation(rad):
if rad > 0 and rad < PI / 2:
return 2*PI + rad
else:
return rad
func move_to_random_point(delta):
# Finds the vector to the target and turns it into an angle in radians
var direction = (target_position - global_position).normalized().angle()
# Finds the distance to the target
var distance = global_position.distance_to(target_position)
# Code to display the point
var a = TRUCK_TRACES.instantiate()
a.global_position = target_position
a.top_level = true
add_child(a)
a = TRUCK_TRACES.instantiate()
a.global_position = Vector2(target_position.x, target_position.y + 10)
a.top_level = true
add_child(a)
if not moving:
moving = true
timer_for_turn.wait_time = 0.01
timer_for_turn.start()
else:
if _rad_to_rad(direction + PI / 2) < 0:
direction = PI-0.1
if time_out_for_turn == true:
time_out_for_turn = false
# An attempt to align the rotation angle and vector to the target.
if _abs_rotation(_abs_rad(rotation)) < _abs_rad(direction + PI / 2):
rotation += rotation_speed * delta
elif _abs_rotation(_abs_rad(rotation)) > _abs_rad(direction + PI / 2):
rotation -= rotation_speed * delta
if global_position.distance_to(target_position) < 100:
moving = false
target_position = _find_random_point()
velocity = -Vector2(0, max_speed)
velocity = velocity.rotated(rotation)
#print(velocity.angle())
#print(rotation)
move_and_slide()
I tried different ways to compare the rotation and angle to the target, trying to change the rotation in through the conditions of more less.
I tried to implement the rotation through the conditions of increasing and decreasing degrees of rotation relative to the target, but at the moment when the target is strictly vertical from the tank, the tank simply begins to zigzag in the direction from the target.
Cat met is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
2