0 votes

This is a function to add tail from my snake game, when it grow.

please help

snake.gd

extends KinematicBody2D

var direction = Vector2(1,0)
const gap = -35
var next_tail_dir = Vector2(1,0)
var prev_dir = Vector2(1,0)
onready var tail = preload("res://snake/tail.tscn")

func _ready():
    add_tail()
    add_tail()
    add_tail()
    add_tail()
    add_tail()
    add_tail()


func _delta():
    if(Input.is_action_pressed("ui_up")):
        direction = Vector2(0,-1)
    elif(Input.is_action_pressed("ui_down")):
        direction = Vector2(0,1)
    elif(Input.is_action_pressed("ui_left")):
        direction = Vector2(-1,0)
    elif(Input.is_action_pressed("ui_right")):
        direction = Vector2(1,0)
    move_snake()

func move_snake():
    var dir_change = false
    if(prev_dir != direction):
        prev_dir = direction
        dir_change = true
    var head_pos = get_node("head").position
    get_node("head").position += direction/2

    if(dir_change):
        for i in range(1,get_child_count()):
            get_child(i).add_to_tail(head_pos, direction)

func add_tail():
    var inst = tail.instance()
    var prev_tail = get_child(get_child_count() -1 )
    if(prev_tail.name != "head"):
        inst.cur_dir = prev_tail.cur_dir
        for i in range(0,prev_tail.pos_array.size()):
            inst.pos_array.append(prev_dir.pos_array[i])
            inst.directions.append(prev_dir.directions[i])
        inst.position = prev_tail.position + prev_tail.cur_dir * gap
    else:
        inst.cur_dir = direction                
        inst.position = prev_tail.position + direction * gap
    add_child(inst)

tail.gd

extends Area2D

var directions = []
var pos_array = []
var cur_dir = Vector2()

func _process(delta):
    if(directions.size() > 0):
        if(position == pos_array[0]):
            cur_dir = directions[0]
            remove_from_tail()
    position += cur_dir/2

func remove_from_tail():
    directions.pop_front()
    pos_array.pop_front()

func add_to_tail(head_pos, dir):
    pos_array.append(head_pos)
    directions.append(dir)
    pass
asked Jun 14 in Engine by Jotapedraw (12 points)

1 Answer

0 votes

Unfortunately, you didn't state in which line of your code the error happens. The error message itself is very clear though: You're trying to access a property called cur_dir on an object that isn't your Tail-scene, but a CollisionShape2D!

If I had to guess, I'd say the error comes from this line:

var prev_tail = get_child(get_child_count() -1)

What is the last child-node of your Snake-scene in the beginning?

answered Jun 15 by njamster (8,874 points)
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.