My goal is to implement a screenshot feature in my game. I need to capture the current viewport as a Texture and assign it to my Sprite. However, the method I tried did not work as expected. The image kept changing whenever the viewport changed, which is not the desired behavior.
How to set texture of Sprite to viewport
- Edited
- Best Answerset by AcoAlex
- The captured viewport after an input (on_CaptureButton_pressed) should be store inside a variable (img).
- Then converted as texture (ImageTexture.create_from_image(img)), stored in another variable (texture)
- Last, set the variable (captured_image) with the prev converted texture (captured_image.set_texture(texture).
https://docs.godotengine.org/en/stable/tutorials/rendering/viewports.html#capture
https://docs.godotengine.org/en/stable/classes/class_imagetexture.html#imagetexture
extends Node
@onready var captured_image = $CapturedImage
func _on_CaptureButton_pressed():
# Retrieve the captured image.
var img = get_viewport().get_texture().get_image()
# Create a texture for it.
var texture = ImageTexture.create_from_image(img)
# Set the texture to the captured image node.
captured_image.set_texture(texture)