Hello, I learnt how to clone an object but I don’t know how to make it teleport to my mouse position after cloning. What I want to do is clone it, make it teleport to my mouse x and y (I’m making a 2D game) and then fall down and stay there. I don’t want the other cloned objects to also teleport to my mouse position so I needed help.,Hello, I am trying to make a script that will clone the object and then teleport to my mouse position and then just fall down. I looked up how to clone an object but when I searched how to teleport it after cloning I couldn’t find anything. Any help is appreciated.
Get the world coordinates for the mouse position:
Vector3 worldPosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
Then you can then send a RaycastHit2D to check if you are able to move an object there:
public LayerMask layerMask;
RaycastHit2D hitData = Physics2D.Raycast(new Vector2(worldPosition.x, worldPosition.y), Vector2.zero, 0, layerMask);
Then you need a reference to the clone you created to move it, or you can instantiate immediately at that location
GameObject newClone = Instantiate(clonePrefab);
newClone.transform.position = worldPosition ;
OR
GameObject newClone = Instantiate(clonePrefab, worldPosition , Quaternion.identity);
Here is an in-depth guide on it: How to convert the mouse position to world space in Unity (2D + 3D) - Game Dev Beginner
Im probably doing something wrong and probably forgot to put some stuff in the script but here it is. I copied your codes to try and got errors.
The Script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class TheAdvancedScript : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
Vector3 worldPosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
public LayerMask layerMask;
RaycastHit2D hitData = Physics2D.Raycast(new Vector2(worldPosition.x, worldPosition.y), Vector2.zero, 0, layerMask);
GameObject newClone = Instantiate(clonePrefab);
newClone.transform.position = worldPosition;
}
}
Errors: