[英]Unity C#: Projectile speed relative to distance between mouse
我在Unity中遇到一個問題,即我試圖用方向和速度實例化彈丸。 方向取決於RotateMouse()函數,該函數計算相對於鼠標的方向(對於射彈)。 標准化后,我將其發送到另一個“彈丸運動”腳本,該腳本會將其乘以速度。
由於某些原因,當我在某個方向上將鼠標靠近字符時,它的運行速度非常慢,而相反方向的距離很長...我也調試了所有值,並且每個“方向”變量在x中都小於1 ,y和z ...
你能發現問題嗎? 行為是盡管標准化,但速度仍在變化,我不了解。
進行方向計算的腳本:
public void RotateMouse()
{
if (Input.GetButton(FindCharacter.FindPlayer(gameObject) + "AimPC"))
{
aimingMouse = true;
sRenderer.enabled = true;
canShoot = true;
var mousePos = Input.mousePosition;
var magePos = Camera.main.WorldToScreenPoint(transform.position);
difference = mousePos - magePos;
difference.Normalize(); // after normalize == direction
rotation_z = Mathf.Atan2(difference.y, difference.x) * Mathf.Rad2Deg;
transform.rotation = Quaternion.Euler(new Vector3(transform.rotation.x, transform.rotation.y, rotation_z + spriteRotationOffset));
}
else
{
aimingMouse = false;
sRenderer.enabled = false;
canShoot = false;
}
}
我實例化彈丸並立即設置方向的另一個腳本:
projectileDir =新的Vector3(controller.difference.x,controller.difference.y,controller.difference.z);
public IEnumerator ShootProjectile(int elementNr)
{
shooting = true;
GameObject projectile = Instantiate(projectilePrefabs[elementNr], instantiatePosition, Quaternion.Euler(0, 0, controller.rotation_z + rotationOffsetZ));
projectile.GetComponent<ProjectileMovement>().Direction(projectileDir);
yield return new WaitForSeconds(shootDuration);
shooting = false;
}
最后,使用方向變量並計算速度:
public class ProjectileMovement : MonoBehaviour {
public float speed;
private Rigidbody2D rb;
private Vector3 direction;
private Collider2D projectileCollider;
private Animator animator;
void Start()
{
rb = GetComponent<Rigidbody2D>();
projectileCollider = GetComponent<Collider2D>();
animator = GetComponent<Animator>();
rb.velocity = speed * direction;
}
public void Direction(Vector3 startingDirection)
{
this.direction = startingDirection;
}
void FixedUpdate()
{
rb.velocity = direction * speed;
}
}
而且,如果您想了解有關腳本的更多信息,我可以提供,但是我想我正在展示與此問題有關的所有內容。 如果不清楚,則可以對其進行評論。
如果問題很難發現,請查看此GIF並觀察火球相對於鼠標指針的速度:
Gyazo gif鏈接
問題是我對Vector3進行了歸一化,並通過首先對Vector2進行歸一化(這給了我不同的/正確的結果)並隨后將x和y值放入Vector3中來利用z維度來解決了問題!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.