Reputation: 81
I'm trying to make my Player Teleport to my mouse position but whenever I right click it seems to teleport far away from my camera and generally where my mouse pointer was. I am not getting any error messages nor am I getting warnings.
for example, if I click in the middle of the screen with my mouse it will teleport to the center of the text Canvas. I couldn't seem to find any solutions to my issue on the unity forums. maybe someone here could help me
my code:
using UnityEngine;
using System.Collections;
public class Player : MonoBehaviour
{
public float moveSpeed;
public float jumpHeight;
public GameObject bullet;
public float speed = 5.0f;
public Transform groundCheck;
public float groundCheckRadius;
public LayerMask whatIsGround;
private bool grounded;
public Transform player; //Variable for Teleport funktion
void Awake()
{
player = GameObject.FindGameObjectWithTag("Player").transform; //Finding the player (Teleport)
}
void fixedUpdate()
{
grounded = Physics2D.OverlapCircle(groundCheck.position, groundCheckRadius, whatIsGround);
}
void Update()
{
if (Input.GetKeyDown("space"))
{
GetComponent<Rigidbody2D>().velocity = new Vector2(GetComponent<Rigidbody2D>().velocity.x, jumpHeight);
}
if (Input.GetKey(KeyCode.D))
{
GetComponent<Rigidbody2D>().velocity = new Vector2(moveSpeed, GetComponent<Rigidbody2D>().velocity.y);
}
if (Input.GetKey(KeyCode.A))
{
GetComponent<Rigidbody2D>().velocity = new Vector2(-moveSpeed, GetComponent<Rigidbody2D>().velocity.y);
}
if (Input.GetMouseButtonDown(1))
{
player.position = (Input.mousePosition); // teleporting
}
if (Input.GetMouseButtonDown(0))
{
Vector2 target = Camera.main.ScreenToWorldPoint(new Vector2(Input.mousePosition.x, Input.mousePosition.y));
Vector2 myPos = new Vector2(transform.position.x, transform.position.y);
Vector2 direction = target - myPos;
direction.Normalize();
Quaternion rotation = Quaternion.Euler(0, 0, Mathf.Atan2(direction.y, direction.x) * Mathf.Rad2Deg);
GameObject projectile = (GameObject)Instantiate(bullet, myPos, rotation);
projectile.GetComponent<Rigidbody2D>().velocity = direction * speed;
}
}
}
Upvotes: 0
Views: 590
Reputation: 545
You just need to transform the input position from screen to world, like you did in your shooting code:
if (Input.GetMouseButtonDown(1))
{
Vector3 target = Camera.main.ScreenToWorldPoint(Input.mousePosition);
player.position = target; // teleporting
}
Upvotes: 2