0 votes
extends Node2D

const SPEED = 200

var velocity = Vector2(0, -1)
var angle = 0
var turn = 0.25 * PI
var time = 32

onready var target = $Sprite

func _ready():
    angle = velocity.angle()

func _physics_process(delta):

    $Sprite.position = get_global_mouse_position()

    time -= 1

    if time == 0:
        var desired = (target.position - $Sprite2.position).normalized()
        desired = desired.angle()

        if desired < angle:
            angle -= turn
        elif desired > angle:
            angle += turn

        velocity = Vector2(round(cos(angle)), round(sin(angle)))

        time = 4

    $Sprite2.position += velocity * (SPEED * delta)

Trying to get one sprite to track another but only allowing it to turn in 45 degree increments. At first, it looks as it it's going to work. Then the tracking sprite just screws off and wanders of screen.

asked Mar 30 in Engine by 9BitStrider (169 points)

1 Answer

+3 votes

For snapping the desired angle, you can use stepify().

For example, this arrow points towards the mouse, but only in 45 degree increments:


extends Node2D

func _process(delta):
    var a = position.direction_to(get_global_mouse_position()).angle()
    rotation = stepify(a, PI/4)
answered Mar 30 by kidscancode (17,168 points)

This works perfectly, but how would I make the angle rotate with a delay like a homing missile?

Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read How to use this Q&A? before posting your first questions.