How to oscillate y-position using cos() relative to the node itself?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By Degermark
extends Node2D

onready var target = $"../target".position
var total_time = 0
var amplitude = 10

func _draw():
	draw_line(Vector2(), target - position, Color.aqua)
func _process(delta):
	target.y = cos(total_time) * amplitude
	total_time += delta

Suppose I have two 2D nodes (“Node2D” and “target”) with a script above attached to “Node2D”. They are both children of 2D node called “Main”.

What I’m having trouble with is that target’s y is oscillating relative to its parent (having sinusoidal peaks relative to its parent), and I want these sinusoidal peaks to be relative to target’s original position that was defined in the scene if that makes sense.

How can I achieve that?

I was looking for a way to have a 3D node oscillate along the y axis, and your method of summing delta and using it in a trig function was perfect.

The only change I made was doing this in the physics_process() function.


Synectome | 2021-06-15 15:17

:bust_in_silhouette: Reply From: DDoop

In the _draw() call, you’re using the Node2D’s position, not the target’s position.
Just to verify, I tried to replicate your scene tree:
This tree, as you’ve described it, is a little unusual. I would try to avoid using a script in one node to regularly determine the actions of another node unless it is explicitly required or helpful. As it stands now, this entire scene could be 1 node: target with an attached script.