- Home /
Move toward Mouse Cursor (RaycastHit), without following?
So with some help from you great people, i have 'finished' this script:
 function Update () {
 
 var hit : RaycastHit;
 if(Physics.Raycast(Camera.main.ScreenPointToRay(Input.mousePosition), hit))
      {
  
  transform.Translate((hit.point - transform.position) * Time.deltaTime, Space.World);
  
  transform.position.z = Mathf.Clamp(transform.position.z, 0, 0);
  
  }
 
 }
This is applied to an instantiated 'bullet' which then moves toward the cursor, but it naturally follows the cursor as it moves.
Where would i begin looking if i wanted it to move toward the cursor direction, and then CONTINUE in that direction without following the cursor?
The 'object' the raycast is hitting is a plane with the mesh renderer taken off.
Thanks for your brain-power, Tom :)
Answer by whydoidoit · Jul 19, 2012 at 03:22 PM
Try something like this:
 var direction: Vector3;
 var speed : float = 2;
 
 function Update () {
 
 var hit : RaycastHit;
 if(Physics.Raycast(Camera.main.ScreenPointToRay(Input.mousePosition), hit))
      {
           direction = (hit.point - transform.position).normalized;
      }
 
  transform.Translate(direction * Time.deltaTime * speed, Space.World);
  transform.position.z = 0;
  
  }
 
 }
It still follows the cursor...BUT!!
Using your idea of the 'direction' variable, i used a 'function Start()' and used AddForce (after sticking a rigid body on the bullet and disabling gravity), and now i get the effect i want:
var direction: Vector3; var speed : float = 2;
function Start () {
var hit : RaycastHit; if(Physics.Raycast(Camera.main.ScreenPointToRay(Input.mousePosition), hit)) { direction = (hit.point - transform.position).normalized; }
rigidbody.AddForce(direction Time.deltaTime speed); transform.position.z = 0;
}
I'd tryed using AddForce before, but it just messed up, you're additional info solved it!
Thank you for helping me with yet another problem :)
WOOPS! Had to put the 'transform.position' into an Update function (else it forgets about it straight away)! :)
var direction: Vector3; var speed : float = 2;
function Start () {
var hit : RaycastHit; if(Physics.Raycast(Camera.main.ScreenPointToRay(Input.mousePosition), hit)) { direction = (hit.point - transform.position).normalized; }
rigidbody.AddForce(direction Time.deltaTime speed);
}
function Update () { transform.position.z = 0; }
Your answer
 
 
              koobas.hobune.stream
koobas.hobune.stream 
                       
                
                       
			     
			 
                