[英]Unity calculate 3D Mouse position
I'm trying to make a C# script for a free throw ball game and need to get the mouse position in the world, and it should be in 3D to be able to throw in all 3 axes. 我正在尝试为罚球游戏制作C#脚本,并且需要获得鼠标在世界上的位置,并且应该在3D模式下才能在所有3个轴上投掷。 I'm kinda new to scripting and the script I wrote works, but not right. 我对脚本编写有点陌生,我写的脚本也不错,但是不对。 I am not sure how to get the depth or the y axis working, because the screen is only 2d . 我不确定如何使深度或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);
}
}
The distance from the camera needs to be set on the z-value of the vector being passed into ScreenPointToRay. 与相机的距离需要在要传递到ScreenPointToRay的向量的z值上进行设置。 The reason why Input.mousePosition works as a parameter for ScreenPointToRay is because Vector2 can be implicitly cast to Vector3. Input.mousePosition用作ScreenPointToRay的参数的原因是因为Vector2可以隐式转换为Vector3。 So try doing something like this: 因此,尝试执行以下操作:
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 is the gameObject reference to the ball that will be thrown. ballGameObject是对将被抛出的球的gameObject引用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.