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.

in Engine by (230 points)

1 Answer

+5 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)
by (21,977 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 Frequently asked questions and How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to [email protected] with your username.