【问题标题】:How to create an object with gdscript?如何使用 gdscript 创建对象?
【发布时间】:2020-07-02 04:06:38
【问题描述】:

如标题所述,我想知道如何在 godot 3.1 中使用 gdscript 创建 3d 对象。我是戈多的新手。我已经搜索并遵循了一些教程,这真的很有帮助。 我想知道怎么做

  1. 创建一个立方体
  2. 为其添加图像纹理
  3. 附加脚本

使用 GDScript。 我才知道这个

var cube1 = MeshInstance.new()

我对场景方法知之甚少,但如果可能的话,我想遵循这个方法。 非常感谢提前

【问题讨论】:

  • 您是打算纯粹通过脚本创建网格、脚本和纹理分配,还是愿意在自己的场景中创建对象,然后实例化该场景?
  • 感谢您的回复,是的,我打算纯粹通过脚本来创建网格、脚本和纹理分配。

标签: game-engine godot gdscript


【解决方案1】:

米尔扎,

最初,您的脚本需要附加到一个父节点。我正在使用一个普通的 Node 对象。将此更改为您的父节点的任何类型。

据我所知,对代码进行了注释,解释了实现您的观点所需的每个步骤。我更改了步骤 13 完成的顺序,因为需要在 将他的节点定义为子节点之前设置脚本给父母。否则,它遵循您所说的相同顺序。

在创建网格之前,您需要一个Physics Object。使用哪个取决于您。

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

希望这会有所帮助。有任何问题,请告诉我。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-11-07
    • 1970-01-01
    • 2020-05-28
    • 1970-01-01
    • 2015-12-06
    • 1970-01-01
    • 2014-06-15
    • 1970-01-01
    相关资源
    最近更新 更多