简体   繁体   中英

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. 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 .

 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. The reason why Input.mousePosition works as a parameter for ScreenPointToRay is because Vector2 can be implicitly cast to 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM