【问题标题】:My Game Character should teleport to the mouse pointer but it teleports far away from my mouse pointer我的游戏角色应该传送到鼠标指针,但它传送到远离我的鼠标指针
【发布时间】:2019-12-11 01:56:42
【问题描述】:

我正在尝试让我的玩家传送到我的鼠标位置,但每当我右键单击时,它似乎传送到远离我的相机并且通常是我的鼠标指针所在的位置。 我没有收到任何错误消息,也没有收到警告。

例如,如果我用鼠标单击屏幕中间,它将传送到文本 Canvas 的中心。 我似乎无法在统一论坛上找到任何解决我的问题的方法。 也许这里有人可以帮助我

我的代码:

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;

        }


    }
}

【问题讨论】:

  • 在您的传送代码正下方有一些射击代码,它将您的Input.mousePosition 从屏幕空间转换 到世界空间。鉴于您需要这个,为什么将player.position 直接设置为屏幕空间坐标有意义?
  • 我真的建议您将GetComponent 返回值存储在变量中以备后用,因为在更新时使用它会导致性能问题

标签: c# unity3d


【解决方案1】:

您只需将输入位置从屏幕转换为世界,就像您在拍摄代码中所做的那样:

if (Input.GetMouseButtonDown(1))
{
    Vector3 target = Camera.main.ScreenToWorldPoint(Input.mousePosition);
    player.position = target; // teleporting

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-24
    • 2013-09-09
    • 2010-09-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多