旋转朝鼠标位置的对象,并触发一些子弹
问题描述:
我有一个游戏物体在我的场景,我想这游戏物体转动,使得它面临着我的鼠标,当我点击它。旋转后,它应该朝着它现在面临的方向移动。但它几乎可行。
例
例如可以说斜边是:4.592912和相邻的是:3.042814,然后我需要MathF.Cos(相邻/斜边)= 0.6625021,现在我采取MathF.Acos(0.6625021) * MathF.Rad2Deg =从现场37.95857
GIF:
代码
float mouseX, mouseY;
float playerX, playerY;
float squaredDeltaX, squaredDeltaY;
float hypotenuse;
int dirX, dirY;
float rotation;
bool mouseClicked = false;
void Update() {
UpdateInputs();
if (mouseClicked)
{
CalcDistance(playerX,playerY,mouseX,mouseY);
SetRotation(squaredDeltaX, squaredDeltaY, hypotenuse);
}
}
void UpdateInputs()
{
Vector3 pos = Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, 0));
mouseX = pos.x;
mouseY = pos.y;
playerX = transform.position.x;
playerY = transform.position.y;
mouseClicked = Input.GetMouseButtonDown(0);
}
void CalcDistance(float x, float y, float x1, float y1)
{
dirX = (x - x1) >= 0 ? 1 : -1;
dirY = (y - y1) >= 0 ? 1 : -1;
squaredDeltaX = (x - x1) * (x - x1);
squaredDeltaY = (y - y1) * (y - y1);
hypotenuse = Mathf.Sqrt(squaredDeltaX + squaredDeltaY);
print("squaredDelta: " + squaredDeltaX + ", " + squaredDeltaY);
print("Hypotenuse: " + hypotenuse);
print("delta: " + Mathf.Sqrt(squaredDeltaX)*dirX + ", " + Mathf.Sqrt(squaredDeltaY)*dirY);
}
void SetRotation(float opposite, float adjacent, float hypotenuse)
{
float tempOpposite = Mathf.Sqrt(opposite);
float tempAdjacent = Mathf.Sqrt(adjacent);
rotation = Mathf.Acos(Mathf.Cos(tempOpposite/hypotenuse));
print("MathF.Cos: " + rotation);
rotation *= Mathf.Rad2Deg * dirX;
print("MathF.Acos: " + rotation);
rotation = dirY != -1 ? rotation + 180 : rotation;
print("angle: " + rotation + "*");
transform.eulerAngles = new Vector3(1,1,rotation);
}
答
下面是使用Mathf.Atan
,Rigidibody2D
和ConstantForce2D
鲁棒方法:
using UnityEngine;
public class NewBehaviourScript : MonoBehaviour
{
private Camera _camera;
private GameObject _find;
private void OnEnable()
{
_find = GameObject.Find("New Sprite");
_camera = Camera.main;
}
private void Update()
{
// find the vector between cannon and mouse position
var p1 = _camera.ScreenToViewportPoint(Input.mousePosition);
var p2 = _camera.WorldToViewportPoint(_find.transform.position);
var p3 = p2 - p1;
// rotate cannon to mouse position
var angle = Mathf.Atan2(p3.y, p3.x) * Mathf.Rad2Deg;
_find.transform.rotation = Quaternion.AngleAxis(angle, Vector3.forward);
// throw a projectile on mouse down
if (Input.GetMouseButtonDown(0))
{
var clone = Instantiate(_find);
var rb = clone.AddComponent<Rigidbody2D>();
rb.gravityScale = 0;
var force = clone.AddComponent<ConstantForce2D>();
force.relativeForce = Vector2.left * 5.0f;
}
}
}
这里的该场景的设置:
(父对象的规模是10)
结果:
注:
你可能会关闭的+/- 90度,在我的例子中,我并没有理会,我刚搬到红小费到适当的地方,我会把它留给你作为练习!
您可以做的另一件事是摧毁不再可见的物体,使用Camera
中使用的方法应该很容易。
非常感谢,我会试试! :) –
欢迎您:-)顺便说一下,使用https://gamedev.stackexchange.com/来提出与游戏相关的问题,对于这些问题,这是一个比这更好的地方! – Aybe