Godot ParallaxBackground 视差背景
程序员文章站
2022-04-30 13:38:17
...
(转存失败,看不到效果到这里吧 http://i.scwy.net/it/2020/033016-godot/ )
效果是这样的:
说明:
- 人物可以自主的休息、走或跑。
- 左上角的数字只是为了标识他跑了多远,以及看出他在休息、跑或者走。
- Timer节点只是让他能随机有些动作变化,以及背景的连动变化。
- 背景分为三层:地面、山、云,它们有不同的运动速度,以体现远近不同。
注意:
- 视差背景需要图片超出视窗比较多的位置,否则会出现部份空白的时候。
- 这里最重要的语句算是 $bg_ground.scroll_offset.x
节点是这样的:
不重要的人物动画:
代码
extends Node2D
export var speed = 1000
var man_speed = 0
func _ready():
randomize()
_on_Timer_timeout()
func _process(delta):
$bg_ground.scroll_offset.x -= delta * man_speed
$bg_mountain.scroll_offset.x -= delta * man_speed/10
$bg_sky.scroll_offset.x -= delta * man_speed/100
$Label.text = str(int($bg_ground.scroll_offset.x))
func _on_Timer_timeout():
var f = randf()
if f>0.9:
$Animated.play("walk")
man_speed = speed / 10
elif f < 0.2:
$Animated.play("idle")
man_speed = 0
else:
$Animated.play("run")
man_speed = speed
给它增加了一些随机效果,比如随时间推移的太阳,地上的花草。随便测试了精灵图片的矩形定位(x,y,width,height)
extends Node2D
export var speed = 200
var man_speed = 0
var dongzuo = ""
var other_rect = [ Rect2(1760,370,80,70),Rect2(1840,370,90,70),Rect2(870,640,120,70),Rect2(510,570,70,70),Rect2(490,960,40,50),Rect2(530,1110,40,50),
Rect2(330,1720,60,60),Rect2(1310,10,50,70),Rect2(1380,30,70,90),Rect2(1150,30,60,50),Rect2(1090,50,50,30),Rect2(880,20,160,160),
Rect2(670,0,190,180),Rect2(170,160,70,80)]
func _ready():
randomize()
_on_Timer_timeout()
func _physics_process(delta):
$bg_ground.scroll_offset.x -= delta * man_speed
$bg_mountain.scroll_offset.x -= delta * man_speed/10
$bg_sky.scroll_offset.x -= delta * man_speed/100
for i in range(1,5):
$bg_ground.get_child(i).position.x -= delta * man_speed
if $bg_ground.get_child(i).position.x < -100:
change_other(i)
OS.set_window_title(dongzuo + " " + str(int($bg_ground.scroll_offset.x/100)))
func _on_Timer_timeout():
$Timer.wait_time = rand_range(3,10)
var f = randf()
if f>0.9:
$Animated.play("walk")
man_speed = speed / 10
dongzuo = "步行"
elif f < 0.2:
$Animated.play("idle")
man_speed = 0
dongzuo = "休息"
else:
$Animated.play("run")
man_speed = speed
dongzuo = "跑"
sun_local()
func change_other(num):
var rnd = int(rand_range(0,len(other_rect)))
var obj = $bg_ground.get_child(num)
obj.position.x = rand_range(1500,2000)
#obj.position.y = 600 - other_rect[rnd].height
obj.region_rect = other_rect[rnd]
#print(other_rect[rnd].x)
# 太阳的位置
func sun_local():
var time = OS.get_datetime().hour + OS.get_datetime().minute/60.0
$bg_mountain/sun.position = Vector2(time * 100 - 750, abs(12.0-time)*50)