[英]Unity calculate 3D Mouse position
我正在嘗試為罰球游戲制作C#腳本,並且需要獲得鼠標在世界上的位置,並且應該在3D模式下才能在所有3個軸上投擲。 我對腳本編寫有點陌生,我寫的腳本也不錯,但是不對。 我不確定如何使深度或y軸正常工作,因為屏幕只有2d。
using UnityEngine;
using System.Collections;
public class ShootBall : MonoBehaviour {
private Rigidbody rb;
private RaycastHit hit;
private Vector3 com;
private Vector3 shootDirection;
void Start () {
rb = GetComponent<Rigidbody>();
}
void Update () {
}
void OnMouseDown (){
com = rb.worldCenterOfMass;
Debug.Log (com);
}
void OnMouseDrag (){
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
Debug.Log(ray);
Physics.Raycast(ray, out hit);
}
void OnMouseUp (){
shootDirection = com - hit.point;
rb.AddForce (shootDirection * 100);
}
}
與相機的距離需要在要傳遞到ScreenPointToRay的向量的z值上進行設置。 Input.mousePosition用作ScreenPointToRay的參數的原因是因為Vector2可以隱式轉換為Vector3。 因此,嘗試執行以下操作:
float distanceFromCamera = Vector3.Distance(ballGameObject.transform.position, Camera.main.transform.position);
Vector3 inputPosition = new Vector3(Input.mousePosition.x, Input.mousePosition.y, distanceFromCamera);
Ray ray = Camera.main.ScreenPointToRay(inputPosition);
ballGameObject是對將被拋出的球的gameObject引用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.