How to create an object with gdscript?

Viewed 3977

as mentioned in the title, I want to know how to create a 3d object with gdscript in godot 3.1. I am new to godot. I have searched and followed some tutorials and that really helped. I want to know how to

  1. create a cube
  2. add image texture to it
  3. attach script to it

with GDScript. I only came to know this

var cube1 = MeshInstance.new()

I know a little about scene approach but I want to follow this one if possible. Many thanks in advance

1 Answers

Mirza,

Initially, your script will need to be attached to a parent node. I'm using a plain Node object. Change this to whatever type your parent node is.

The code is commented, explaining each step required to fulfill your points, to the best of my knowledge. I've changed the order which steps 1 and 3 are done, as a script needs to be set before his node is defined as a child to a parent. Otherwise, it follows the same sequence you've stated.

Before having a mesh created, you need a Physics Object. Which you use is up to you.

extends Node  # or whatever object type it's attached to

# Preloads script to be attached
const my_script = preload("res://Scripts/your_script.gd")

func _ready():  # Runs when scene is initialized
    # STEP 1: add a cube to the scene
        # Step 1.1, create a Physics body.
        # I'm using a static body but this can be any
        # other type of Physics Body
    var cube = StaticBody.new()
    cube.transform.origin = Vector3(0, 0, 0)  # change initial pos here

    # STEP 3: attach script
        # It is actually required to have the script
        # attached before a node is defined as a child node
        # to the parent. So your step 3 goes here
    cube.set_script(my_script)

    self.add_child(cube)  # Add as a child node to self
        # Step 1.2, add a collision shape to the
        # Physics body, defining its shape to a Box (cube)
    var coll = CollisionShape.new()
    coll.shape = BoxShape.new()
    cube.add_child(coll)  # Add as a child node to cube
        # Step 1.3, add a mesh, so that it's visible
    var mesh = MeshInstance.new()
    mesh.mesh = CubeMesh.new()
    cube.add_child(mesh)  # Add as a child to cube

    # STEP 2: change texture
        # Step 2.1, load your texture from pc
    var new_texture = ImageTexture.new()
    new_texture.load("res://path/to/new_texture.png")
        # Step 2.2, get material from cube
    var cube_material = mesh.get_surface_material(0)
        # Step 2.3, change texture from material to your new texture
    cube_material.albedo_texture = new_texture

Hope this helps. Any questions, let me know.

Related