Reputation: 14151
I have a player sprite that moves anywhere on the screen clicked. I am trying to make a player info panel popup if the player sprite is clicked.
But unfortunately I only get the player moving a couple of pixels. I have a Box Collider 2d
added to the sprite and an event trigger set to Pointer Click to run the method ShowPlayerInfoPanel
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class PlayerController : MonoBehaviour {
//Player Movement
float speed = 2f;
Vector2 targetPos;
private Rigidbody2D myRigidbody;
private Animator myAnim;
private static bool playerExists;
public static PlayerController instance;
public string exitPortal;
public bool startMoving;
public float smoothTime = 0.3F;
private Vector3 velocity = Vector3.zero;
//Player Info
public string displayName;
public string coins;
//Player Panel display
public GameObject playerInfoPanel;
private void Start()
{
myRigidbody = GetComponent<Rigidbody2D>();
myAnim = GetComponent<Animator>();
if(instance == null){
instance = this;
} else {
Destroy(gameObject);
}
DontDestroyOnLoad(transform.gameObject);
targetPos = transform.position;
}
void Update()
{
if (Input.GetMouseButtonDown(0))
{
targetPos = (Vector2)Camera.main.ScreenToWorldPoint(Input.mousePosition);
startMoving = true;
}
if ((Vector2)transform.position != targetPos && startMoving)
{
Move();
} else {
myAnim.SetBool("PlayerMoving", false);
}
}
void Move()
{
Vector2 oldPos = transform.position;
transform.position = Vector2.MoveTowards(transform.position, targetPos, speed * Time.deltaTime);
//transform.position = Vector3.SmoothDamp(transform.position, targetPos, ref velocity, smoothTime);
Vector2 movement = (Vector2)transform.position - oldPos;
myAnim.SetBool("PlayerMoving", true);
myAnim.SetFloat("Horizontal", movement.x);
myAnim.SetFloat("Vertical", movement.y);
}
public void ShowPlayerInfoPanel()
{
Debug.Log("hi");
PlayerInfoPanel playerInfo = playerInfoPanel.GetComponent<PlayerInfoPanel>();
playerInfo.DisplayName.text = displayName;
playerInfo.Coins.text = coins;
playerInfoPanel.SetActive(true);
}
}
Upvotes: 1
Views: 667
Reputation: 4343
With a collider on your gameObject you can just use OnMouseDown to detect when the object is clicked.
void OnMouseDown()
{
ShowPlayerInfoPanel();
}
Upvotes: 3