简体   繁体   English

Unity-使玩家指向鼠标

[英]Unity - Make player point toward mouse

Im making a top-down shooter, where the player moves up, down, left, and right with WASD and constantly points toward the mouse. 我正在制作一个自上而下的射击游戏,玩家可以通过WASD上下左右移动,并不断指向鼠标。 I want the movement to be irrelevant to the direction the player is pointing, but right now thats not the case. 我希望动作与玩家指向的方向无关,但现在情况并非如此。

Here is my code: 这是我的代码:

void Update() 
{
  float igarH = Input.GetAxisRaw("Horizontal");
  float igarV = Input.GetAxisRaw("Vertical");
  if (igarH > 0.5f || igarH < -0.5f) 
  {
    transform.Translate(new Vector3(igarH * moveSpeed * Time.deltaTime, 0f, 0f));
  }
  if (igarV > 0.5f || igarV < -0.5f)
  {
    transform.Translate(new Vector3(0f, igarV * moveSpeed * Time.deltaTime, 0f));
  }

  // Point toward mouse
  Vector2 direction = Camera.main.ScreenToWorldPoint(Input.mousePosition) - transform.position;
  float angle = Mathf.Atan2(direction.y, direction.x) * Mathf.Rad2Deg;
  Quaternion rotation = Quaternion.AngleAxis(angle, Vector3.forward);
  transform.rotation = rotation;
}

Sorry about the bad indentation, its kind of hard to figure out how the site wants me to do the markup, and I'm new to this site. 很抱歉,缩进不好,很难弄清楚该网站希望我如何进行标记,而且我是这个网站的新手。

Why is the player moving differently based on where my mouse is? 为什么播放器会根据鼠标的位置进行不同的移动? I want movement to be the same no matter what. 无论如何我都希望动作保持相同。

Please keep all answers related to Unity2D and not 3D, please. 请保留所有与Unity2D而非3D有关的答案。

Transform.Translate has an optional parameter relativeTo , in that you choose if you want the object to move relative to its own corrdinate system or the world coordinate system. Transform.Translate有一个可选参数relativeTo ,您可以选择是否要相对于其自身的坐标系或世界坐标系来移动对象。

Just change your calls to: 只需将您的电话更改为:

if (igarH > 0.5f || igarH < -0.5f) {
  transform.Translate(new Vector3(igarH * moveSpeed * Time.deltaTime, 0f, 0f), Space.World);
}
if (igarV > 0.5f || igarV < -0.5f) {
  transform.Translate(new Vector3(0f, igarV * moveSpeed * Time.deltaTime, 0f), Space.World);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM