Topic was automatically imported from the old Question2Answer platform.
Asked By
bgegg
extends Node2D
var path = load("res://0_practice_folder/add_mesh_2d/Sprite.tscn")
var ins
var v_rect
func _input(event):
if Input.is_mouse_button_pressed(BUTTON_LEFT):
v_rect = get_viewport_rect().size
ins = path.instance()
ins.set_position(Vector2(stepify(event.position.x,64) ,stepify(event.position.y,64)) - v_rect/2)
self.add_child(ins)
i done add sprite to click position by this code.
however ,texture overlap in same cell.
it must judged by boolean whether the texture already exists.
i also need to replace the textures
I think i should probably number the cells.
onready var path = preload("res://0_practice_folder/add_mesh_2d/Sprite.tscn")
const GRID_SIZE = Vector2(64, 64)
func _input(event):
if Input.is_mouse_button_pressed(BUTTON_LEFT):
var ins = path.instance()
self.add_child(ins)
ins.global_position = get_global_mouse_position().snapped(GRID_SIZE)
Try this. Position should be set after instancing. I might have done some typo with the get mouse pos, but you should find it in the documentation if not
Thank you very much.
I was able to add sprites this way too.
You need to check on which one of the tiles does the mouse land.
If, for example, your tiles are 64 pixels by 64 pixels tall, and they cover all of the screen, then you can do
var mouse_pos = get_viewport().get_mouse_position()
#This should give you the position of your cursor
var tile = Vector2(mouse_pos.x/64 , mouse_pos.y/64)
#This will tell you the tile the mouse is on, for example row 5 column 3
Note that the number 64 must be the size of your tiles, not specifically 64.
Then, if your mouse is on say, row 5 column 3 and you want to draw your sprite in the middle of the square, you should draw it in the position (tile.x64 + 32, tile.y64 + 32)
That “+32” is there to place it on the middle of the tile.
Also, note that if your grid doesn’t cover all of the screen but actually starts for example in the position (256, 256) then you should put that into your code like:
var tile = Vector2((256 + mouse_pos.x)/64 , (256 + mouse_pos.y)/64)
#This will tell you the tile the mouse is on, for example row 5 column 3
Try this and tell me if it works, good luck!
I’m still trying out the code, can I prevent overlap?