Question by
XALO1 · Mar 26, 2020 at 08:44 AM ·
cursormousepositionmouselook
hi i want to moved my target (cube) on screen with my mouse cursor. I'm following a tutorial and this script works on that tutorial. my unity version is 5.5.1
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GameManager : MonoBehaviour {
public GameObject Ball;
Plane plane = new Plane(Vector3.forward,0);
public Transform target;
void Update () {
Vector3 dir = target.position - Ball.transform.position;
if(Input.GetMouseButtonDown(0))
{
Ball.GetComponent<Rigidbody> ().AddForce (Vector3.forward, ForceMode.Impulse);
}
float dist;
Ray ray = Camera.main.ScreenPointToRay (Input.mousePosition);
if (plane.Raycast(ray, out dist))
{
Vector3 point = ray.GetPoint (dist);
target.position = new Vector3 (point.x,point.y,0);
}
}
}
Comment
Answer by streeetwalker · Mar 26, 2020 at 09:34 AM
..... .AddForce (Vector3.forward, ForceMode.Impulse);
I think this should be:
..... .AddForce (dir, ForceMode.Impulse);
You calculate the direction from the ball to target, so you need to use that as the direction of the force.
However there are some problems with that if the ball z is not zero: target point is at z=0, and if the ball transform z is not zero, the direction is pointing at the target in the correct x and y direction, but pointing into the ground. The affect will be, if ball z is not zero, to slow the ball down if it is touch a "ground" plane or other object. Seems like the tutorial didn't take that into account?
Your answer
![](https://koobas.hobune.stream/wayback/20220612225750im_/https://answers.unity.com/themes/thub/images/avi.jpg)