I'm trying, without success, to access the data of a mesh from a MeshInstance node.
I've imported a 3d object, opened it as "New Inherited", turned it as "Unique" and saved it as foo.mesh. Then, on a new scene, I did create a MeshInstance and loaded the foo.mesh as its Mesh.
The Script is attached to the very MeshInstance, kinda like follows:
extends MeshInstance
func _ready():
var themesh = Mesh
var mdt = MeshDataTool.new()
if mdt.create_from_surface(themesh, 0):
print("Ok!!")
print(mdt.get_vertex_count()) # get_vertex_count() returns 0
else:
print("Failed...")
It doesn't work for built in meshes. Needs to be an imported mesh, that I also save as a Godot .mesh.
Reference links: Facebook, Mesh Data Tool, Mesh Class
I was mistaking pointing to Mesh class instead of mesh attribute to get the mesh reference. And the if test needs to check pass, because "create_from_surface()" returns a non zero when an error occours.
extends MeshInstance
func _ready():
var themesh = mesh # Same as bellow, points to same object in memory
var themesh2 = self.get_mesh() # Same as above, points to same object in memory
print("Mesh surface count: " + str(themesh.get_surface_count()))
var mdt = MeshDataTool.new()
if mdt.create_from_surface(themesh, 0) == OK: # Check pass
print("Ok!!")
print(mdt.get_vertex_count())
else:
print("Fail...")
var aMeshVerts = []
for i in range(mdt.get_vertex_count()):
aMeshVerts.append(mdt.get_vertex(i)) # Storing the vertices positions
mdt.set_vertex(0, Vector3(1, 2, 1)) # Changing a vertice position
themesh.surface_remove(0)
mdt.commit_to_surface(themesh)
mdt.clear()
Related
I'm making a game that's top down and has enemies. They don't shoot just walk at you. Well there supposed too. I just can't seem to get to enemies to be able to locate the player even if the player is the parent node.
This is the code here:
extends KinematicBody2D
var health: int = 100
var motion = Vector2()
var speed = 100
func _on_Area2D_body_entered(body):
yield(get_tree().create_timer(0.1), 'timeout')
if "Bullet" in body.name:
health -= 20
if health <= 1:
queue_free()
func _physics_process(delta):
var Player = get_parent().get_node("Player")
position += (Player.position - position)/50
look_at(Global.player.global_position)
move_and_collide(motion)
but all I get from this is an error saying: Invalid get index 'position' (on base: 'null instance').
I don't understand what's going here. So far I've had to make the Player the parent but I also need to make it the main scenes parent so I can instance it so there are multiple of them. That's literally impossible in Godot standards. another question is I'm trying to make the enemies spawn around a moving camera but all they do is go to one corner.
My code is as showed in a camera 2d :https://youtu.be/klBvssJE5Qg
extends Node2D
onready var camera_x = $Player/playercamera.global_position.x
onready var camera_y = $Player/playercamera.global_position.y
var normal_zombie = preload("res://scenes/Enemy.tscn")
var player = null
func _on_Timer_timeout():
var enemy_position = Vector2(rand_range(-510, 310), rand_range(510, -310))
while enemy_position.x < 510 and enemy_position.x > -510 and enemy_position.y < 310 and enemy_position.y > -310:
enemy_position = Vector2(rand_range(-510, 310), rand_range(510, -310))
var normal_zombie_instance = normal_zombie.instance()
normal_zombie_instance.position = enemy_position
add_child(normal_zombie_instance)
Last problem I'm facing is that I made it so the zombies had 100 health and would die at 0. Whenever a bunch spawn(ed) (I tried fixing it but ended up making it worse) and I killed 2 at the same time it would just crash. The codes here.
func _on_Area2D_body_entered(body):
yield(get_tree().create_timer(0.1), 'timeout')
if "Bullet" in body.name:
health -= 20
if health <= 1:
queue_free()
If you read all of this your a legend. If you helped me out with all the questions I would've given you boba tea. To bad I don't know where you live and can't send it to you. Please someone answer :3
UwU
I have looked up many many ways to do it. I only use stack overflow if it's my last hope. Please help!!!
Before looking at anything else, you say you have this error:
Invalid get index 'position' (on base: 'null instance')
This is not hard to understand. You have a null and you are trying to get position of it.
And looking at the code, that got to be here:
func _physics_process(delta):
var Player = get_parent().get_node("Player")
position += (Player.position - position)/50
look_at(Global.player.global_position)
move_and_collide(motion)
More precisely, here:
position += (Player.position - position)/50
So Player is null. So this get_parent().get_node("Player") gave you null.
Please notice that get_parent().get_node("Player") is looking for a sibling. It literally wants to get a child called "Player" from the parent. A child from the parent. A sibling.
I'll also point out that get_parent().get_node("Player") is equivalent to get_node("../Player") which is equivalent to $"../Player". If you need to put the Player somewhere else, update the path accordingly.
Let us break this code down:
extends Node2D
onready var camera_x = $Player/playercamera.global_position.x
onready var camera_y = $Player/playercamera.global_position.y
var normal_zombie = preload("res://scenes/Enemy.tscn")
var player = null
func _on_Timer_timeout():
var enemy_position = Vector2(rand_range(-510, 310), rand_range(510, -310))
while enemy_position.x < 510 and enemy_position.x > -510 and enemy_position.y < 310 and enemy_position.y > -310:
enemy_position = Vector2(rand_range(-510, 310), rand_range(510, -310))
var normal_zombie_instance = normal_zombie.instance()
normal_zombie_instance.position = enemy_position
add_child(normal_zombie_instance)
First of all, here you are taking a copy of these values when the Node is ready:
onready var camera_x = $Player/playercamera.global_position.x
onready var camera_y = $Player/playercamera.global_position.y
And second I don't see you update them or use them.
I would, instead have a reference to the camera. Which assuming these lines are correct would be like this:
onready var camera = $Player/playercamera
Which means that the Player is a child of this Node, and playercamera is a child of Player. If you need to put the camera somewhere else, you can update the path accordingly.
Then (I assuming the indentation problem was when posting the code here), you have this:
func _on_Timer_timeout():
var enemy_position = Vector2(rand_range(-510, 310), rand_range(510, -310))
while enemy_position.x < 510 and enemy_position.x > -510 and enemy_position.y < 310 and enemy_position.y > -310:
enemy_position = Vector2(rand_range(-510, 310), rand_range(510, -310))
var normal_zombie_instance = normal_zombie.instance()
normal_zombie_instance.position = enemy_position
add_child(normal_zombie_instance)
You are using position, which as I said in the other answer is relative to the parent. And the parent is not not the camera. Quite the opposite, the camera is a child of the Player, which is a child of this Node.
Instead set the global_position (or the global_transform.origin if you prefer) to camera.to_global(enemy_position) (where camera is the reference to the camera).
In the other answer mentioned to use camera.to_global if the camera was not the parent but you had a reference to it. You are not forced to make it a parent.
Note: The global_position is not relative to the parent, but to the world.
And about the crash (also assuming the indentation problem was posting the code here), you have this:
func _on_Area2D_body_entered(body):
yield(get_tree().create_timer(0.1), 'timeout')
if "Bullet" in body.name:
health -= 20
if health <= 1:
queue_free()
I want you to imagine the following scenario:
A first body enters.
The execution for the first body reaches yield.
After the timeout the execution for the first body resumes and reaches queue_free.
A second body enters, the same frame that queue_free was called.
The execution for the second reaches yield.
Godot frees the Node (because you had called queue_free).
After the timeout… Eh? Godot cannot resume the execution for the second body because the Node was freed.
That is not the only way it can happen. It is just the easier to explain because it is the most sequential scenario. It could also be something like this:
A first body enters.
The execution for the first body reaches yield.
A second body enters.
The execution for the second reaches yield.
After the timeout the execution for the first body resumes and reaches queue_free.
Godot frees the Node (because you had called queue_free).
After the timeout… Eh? Godot cannot resume the execution for the second body because the Node was freed.
I bring this up because the way I described it earlier might suggest to you that you can avoid this problem simply by using is_queued_for_deletion but that is not the case.
Even if you were to fix that for this method, anything else that was pending in yield when the Node was freed would be an issue. Thus, you have two solutions:
Don't call queue_free unless you know nothing is pending in yield.
Don't use yield.
There are gotchas and caveats. I'll point you to Are Yields a Bad Code Practice in GDScript?.
I'll side on not using yield in this case. So my fix would be like this:
func _on_Area2D_body_entered(body):
get_tree().create_timer(0.1).connect("timeout", self, take_damage, [20])
func take_damage(amount) -> void:
health -= amount
if health <= 1:
queue_free()
In principle it is the same idea. You are creating a timer, and when the timer emits the "timeout" signal it will execute some code. The difference is that we didn't use yield, instead we connected to the signal, and when a Node is freed Godot disconnect any signals it might have connected.
I have said a couple times that you can update a path according to where the Nodes are relative to each other. You could also export a NodePath which I also mentioned in the other answer and set it via the inspector. For the camera example, it could be like this:
export var camera_path:NodePath
onready var camera = get_node(camera_path)
With the caveat that, as I mentioned earlier, the value of the onready variable is a copy taken when the Node is ready. So, changing the camera_path in runtime won't update the camera, you could handles that using setget if you need to.
I am going to, once more, point you to Nodes and scene instances, and see the documentation on NodePath too.
In Godot I am trying to make a simple space shooter game where the player has to destroy a certain amount of enemies to get to the next level of the game. I am trying to get the enemy's to shoot the player to make the game a bit more fun but I am getting an error that I have no idea how to fix
invalid get index 'position' (on base: Nil).
I think the problem here is that the variable position is showing up as null but I don't know how to fix it
Script:
extends StaticBody2D
var dir = Vector2()
var player
var bullet = preload("res://scebes/EnemyBullet.tscn")
func _ready():
_get_dir(player)
func _get_dir(target):
dir = (target.position - position).normalized()
func _on_Timer_timeout():
_get_dir(player)
var b = bullet.instance()
get_parent().add_child(b)
b.position = position + dir * offset
b.dir = dir
With the error appearing on the line:
dir = (target.position - position).normalized()
Scene tree:
Node2D
├ Player
│ └ (...)
├ simple
│ ├ Sprite
│ └ CollisionShape2D
└ enemy
├ Sprite
├ CollisionShape2D
└ Timer
With the timeout of the Timer signal connected to _on_Timer_timeout.
Superficial Diagnose
The error is telling you that you are trying to access position on something that is null.
In the line:
dir = (target.position - position).normalized()
You try to access position of target (target.position) and position of self (position). Where self is the object that has the script attached. Evidently self is not null. So, let it has to be target.
The code gets target as parameter:
func _get_dir(target):
dir = (target.position - position).normalized()
Symptomatic Treatment
You would get rid of the error if you null check target:
The code gets it as parameter:
func _get_dir(target):
if target == null:
return
dir = (target.position - position).normalized()
Or better yet, check with is_instance_valid:
func _get_dir(target):
if not is_instance_valid(target):
return
dir = (target.position - position).normalized()
That way it will also handle the case where target is not null, but it references a deleted node. There are more checks you could do such as is_inside_tree or is_queued_for_deletion, but usually you don't need those.
However, that does not get rid of the real problem. The real problem is why target is null to begin with.
Deeper Diagnose
So, where is _get_dir called? Here:
func _ready():
_get_dir(player)
And later, here:
func _on_Timer_timeout():
_get_dir(player)
# ...
And where does player gets it value? Nowhere. That is the real problem. The variable player is not initialized.
Solution 1 (Simple, Fragile)
Presumably you want player to reference the Player node on the scene tree, right?
And we need to do it just in time for _ready. So we need to either insert lines at the start of _ready, or do it in an onready var.
This is possible, even though, it is fragile code:
onready var player := get_node("../Player")
The problem with that is that it assumes that the node with this script and the Player node are siblings. Which might not be true in the future. That is, reorganizing the scene tree would break the code. Hence, we say the code is fragile (easy to break).
Solution 2 (Complex, Robust)
We are in this situation becase the enemy (I'm assuming this code in the enemy) always knows where the player is. These are omniscient enemies. Thus, another option is to embrace that.
You can create an autoload (singleton). To do that, begin by creating a new script (secondary click on the FileSystem panel and select "New Script...") that looks like this:
var player
Perhaps type it (Node2D, KinematicBody2D or whatever):
var player:Node2D
Register it as an autoload on project settings with some name, let us say PlayerInfo.
Now, the player needs to register itself:
func _ready() -> void:
PlayerInfo.player = self
And the enemy can find it like this:
func _ready() -> void:
player = PlayerInfo.player
Plot twist: this code is still fragile, because the order in which _ready execute depends on the scene tree.
To avoid that, you can skip a frame in _ready before reading PlayerInfo.player:
func _ready() -> void:
yield(get_tree(), "idle_frame")
player = PlayerInfo.player
That way, you are sure Player had a chance to set PlayerInfo.player.
You may also register the player in _enter_tree:
func _enter_tree() -> void:
PlayerInfo.player = self
The _enter_tree method would run before _ready for a given node. But not necessarily before _ready of another node.
Another thing you can do is get rid of the player variable and use PlayerInfo.player directly:
_get_dir(PlayerInfo.player)
So even if the code got null the first time, it would not be stuck with that null.
By the way, you could use PlayerInfo.player from any node.
By the way, do you remember the extra checks? you could have them in the autoload:
var player:Node2D setget , get_player
func get_player() -> Node2D:
if not is_instance_valid(player):
# player is null, or deleted
return null
if not player.is_inside_tree():
# player has not been added or has been removed form the scene
return null
if player.is_queued_for_deletion():
# player is queued for deletion (e.g. queue_free)
return null
return player
Which would run every time PlayerInfo.player is read.
Note: there are other reasons to have an autoload that references the player in some way. For example, you could put save and load game functionality there. Or it can help you move the player from one scene to another. Thus, this extra complexity may proof useful in the long run, for big games.
In Godot i'm trying to get a kinematic body to teleport to the position of the mouse and i get this error: Invalid set index 'position' (on base: 'KinematicBody') with value of type 'Vector3'.I don't want to use move and slide as I want the item to be teleported to the mouse, not move towards the mouse
My code:
extends KinematicBody
# Declare member variables here. Examples:
# var a = 2
# var b = "text"
# Called when the node enters the scene tree for the first time.
func _ready():
pass # Replace with function body.
# Called every frame. 'delta' is the elapsed time since the previous frame.
func _process(delta):
if (Input.is_action_pressed("ui_right")):
rotate_y(-0.1)
elif (Input.is_action_pressed("ui_left")):
rotate_y(0.1)
elif (Input.is_action_pressed("ui_up")):
rotate_z(0.1)
elif (Input.is_action_pressed("ui_down")):
rotate_z(-0.1)
var tempPosition = place()
print(tempPosition)
if tempPosition != null:
var temp_mesh =get_tree().get_root().get_node("World/TestBody")
temp_mesh.position = tempPosition
func _input(event):
if event is InputEventMouseMotion:
rotate_y(-event.relative.x * 0.0002)
$pivot.rotate_x(-event.relative.y * 0.0002)
$pivot.rotation.x = clamp($pivot.rotation.x, -1.2, 1.2)
# Place an item
func place():
var ray_length = 5000
var mouse_pos = get_viewport().get_mouse_position()
var camera = get_node("pivot/Camera")
var from = camera.project_ray_origin(mouse_pos)
var to = from + camera.project_ray_normal(mouse_pos) * ray_length
var space_state = get_world().get_direct_space_state()
var result = space_state.intersect_ray(from, to)
if result:
return result.position
KinematicBody does not have a position property (only KinematicBody2D does). For 3D Spatial objects like KinematicBody, you should use global_transform.origin.
I want to code a Qt3DWindow where I would have two QLayer-s, QLayerFilter-s, QViewport-s, etc. I need this because I want to render entities in QViewport 1 in a usual way and entities in QViewport 2 always visible (even when they are actually behind entities 1).
Here is my code:
class Window(Qt3DExtras.Qt3DWindow):
def __init__(self):
super().__init__()
self.root_entity = Qt3DCore.QEntity()
self.entity_1 = Qt3DCore.QEntity(self.root_entity)
self.entity_2 = Qt3DCore.QEntity(self.root_entity)
self.setRootEntity(self.root_entity)
# some other code
self.surselector = Qt3DRender.QRenderSurfaceSelector()
self.surselector.setSurface(self)
# Viewport 1
self.viewport_1 = Qt3DRender.QViewport(self.surselector)
self.layerfilter_1 = Qt3DRender.QLayerFilter(self.viewport_1)
self.layer_1 = Qt3DRender.QLayer(self.entity_1)
self.entity_1.addComponent(self.layer_1)
self.layer_1.setRecursive(True)
self.layerfilter_1.addLayer(self.layer_1)
self.cameraSelector_1 = Qt3DRender.QCameraSelector(self.layerfilter_1)
self.clearBuffers_1 = Qt3DRender.QClearBuffers(self.cameraSelector_1)
self.cameraSelector_1.setCamera(self.camera())
self.clearBuffers_1.setBuffers(Qt3DRender.QClearBuffers.AllBuffers)
# Viewport 2
self.viewport_2 = Qt3DRender.QViewport(self.surselector)
self.layerfilter_2 = Qt3DRender.QLayerFilter(self.viewport_2)
self.layer_2 = Qt3DRender.QLayer(self.entity_2)
self.entity_2.addComponent(self.layer_2)
self.layer_2.setRecursive(True)
self.layerfilter_2.addLayer(self.layer_2)
self.cameraSelector_2 = Qt3DRender.QCameraSelector(self.layerfilter_2)
self.clearBuffers_2 = Qt3DRender.QClearBuffers(self.cameraSelector_2)
self.cameraSelector_2.setCamera(self.camera())
# The line below causes that no entity appears
self.clearBuffers_2.setBuffers(Qt3DRender.QClearBuffers.AllBuffers)
# The code below is what make viewport 2 / layer 2 / layerfilter 2 different from view port 1 / etc.
self.rendstate_2 = Qt3DRender.QRenderStateSet(self.clearBuffers_2)
self.rendstate_2.setParent(self.clearBuffers_2)
depth = Qt3DRender.QDepthTest()
depth.setDepthFunction(Qt3DRender.QDepthTest.LessOrEqual)
self.rendstate_2.addRenderState(depth)
self.setActiveFrameGraph(self.surselector)
If I understand correctly you want both viewports be drawn over each other (i.e. not in left and right half), while the first one draws all normal entities and the second one the ones that are always visible.
First of all, I think you don't need the viewports. Qt defaults this to the rectangle (0, 0, 1, 1) if none is present, but I'm not sure about this.
The actual issue is this line
self.clearBuffers_2.setBuffers(Qt3DRender.QClearBuffers.AllBuffers)
because here you delete the color buffer as well, which deletes everything the first viewport rendered. Try setting it to Qt3DRender.QClearBuffers.DepthBuffer. This only clears your depth buffer.The entites of the second viewport will be drawn ontop of the rendering of the first viewport.
personally pretty new to programming and I am trying to save a high mp Image from an IDS camera using the pyueye module with python.
my Code works to save the Image, but the Problem is it saves the Image as a 1280x720 Image inside a 4192x3104
I have no idea why its saving the small Image inside the larger file and am asking if anyone knows what i am doing wrong and how can I fix it so the Image is the whole 4192x3104
from pyueye import ueye
import ctypes
hcam = ueye.HIDS(0)
pccmem = ueye.c_mem_p()
memID = ueye.c_int()
hWnd = ctypes.c_voidp()
ueye.is_InitCamera(hcam, hWnd)
ueye.is_SetDisplayMode(hcam, 0)
sensorinfo = ueye.SENSORINFO()
ueye.is_GetSensorInfo(hcam, sensorinfo)
ueye.is_AllocImageMem(hcam, sensorinfo.nMaxWidth, sensorinfo.nMaxHeight,24, pccmem, memID)
ueye.is_SetImageMem(hcam, pccmem, memID)
ueye.is_SetDisplayPos(hcam, 100, 100)
nret = ueye.is_FreezeVideo(hcam, ueye.IS_WAIT)
print(nret)
FileParams = ueye.IMAGE_FILE_PARAMS()
FileParams.pwchFileName = "python-test-image.bmp"
FileParams.nFileType = ueye.IS_IMG_BMP
FileParams.ppcImageMem = None
FileParams.pnImageID = None
nret = ueye.is_ImageFile(hcam, ueye.IS_IMAGE_FILE_CMD_SAVE, FileParams, ueye.sizeof(FileParams))
print(nret)
ueye.is_FreeImageMem(hcam, pccmem, memID)
ueye.is_ExitCamera(hcam)
The size of the image depends on the sensor size of the camera.By printing sensorinfo.nMaxWidth and sensorinfo.nMaxHeight you will get the maximum size of the image which the camera captures. I think that it depends on the model of the camera. For me it is 2056x1542.
Could you please elaborate on the last sentence of the question.