![](/img/trans.png)
[英]Unity 3D, How can I detect if mouse is over a 2D Sprite even if the Sprite is not visible
[英]Move forward a sprite 2d in clicking on it in Unity 3d
统一版本:2021.1.24f1
您好,目前我正在使用 Unity 3d 创建一个 2D 游戏; 我希望当我用鼠标单击并且 cursor 在我的精灵上方时,它会上升 15 个像素; 它垂直和水平移动
我的脚本:
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
Rigidbody m_Rigidbody;
float m_speed;
void Start(){
m_Rigidbody = GetComponent<Rigidbody>();
m_speed = 5f;
}
void Update()
//bouton gauche de la souris
{if (Input.GetMouseButtonDown(0)){
m_Rigidbody.velocity = transform.forward(new Vector2(0,-1) * Time.deltaTime * m_speed, Space.World);
}
//bouton droit de la souris
if(Input.GetMouseButtonDown(1)){
m_Rigidbody.velocity = transform.forward(new Vector2(-1, 0) * Time.deltaTime*m_speed, Space.World);
}
//roulette de la souris
if(Input.GetMouseButtonDown(2)){
m_Rigidbody.velocity = transform.forward (new Vector2(0,-1) * Time.deltaTime * m_speed, Space.World);
}
}
}```
您所犯的错误之一是您在 2D 游戏中使用了刚体组件。 您应该使用 Rigidbody2D 组件。
另一个,你在下面所说的错误是你使用transform.forward
作为一种方法,而实际上它只是一个Vector3(0,0,1) 。 因此,如果您想 go 向上(不是向前,它是 2D),只需单独使用transform.up
或new Vector2(0,1)
而不用彼此相乘,这真的没有意义。
您也不应该直接修改 rb.velocity 值,我什至不知道它是否可能。 有一个内置的 Unity function, Rigidbody2D.AddForce(Vector2)
所以尝试使用:
m_Rigidbody.AddForce(transform.up * Time.deltaTime * m_speed);
那应该行得通。 我也不知道你为什么要改变随时间增加的速度/力,因为这会使播放器 go 越来越快,但这是你的代码。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.