- Home /
How can I make a grappling hook with RayCast?
I'm trying to make a game where I can move to targets with Raycast. I figured the code would work in the opposite way that the I can pull things to me but it isn't working.
var target : Transform;
var target1 : Transform;
function Start()
{
Screen.showCursor = false;
}
function Update ()
{
if(Input.GetButton("Fire1"))
{
var ray1 : Ray = camera.ViewportPointToRay (Vector3(0.5,0.5,0));
var hit1 : RaycastHit;
if (Physics.Raycast (ray1, hit1,100))
{
if(hit1.transform.tag == "Pullable")
{
hit1.transform.position = Vector3.MoveTowards(hit1.transform.position, target.position,Time.deltaTime * 25);
hit1.transform.LookAt(target);
}
}
Debug.DrawLine (ray1.origin, hit1.point, Color.red);
}
if(Input.GetButton("Fire2"))
{
var ray2 : Ray = camera.ViewportPointToRay (Vector3(0.5,0.5,0));
var hit2 : RaycastHit;
if (Physics.Raycast (ray2, hit2,100))
{
if(hit2.collider.gameObject.tag == "Teleport")
{
transform.position = Vector3.MoveTowards(transform.position, target1.position,Time.deltaTime * 25);
transform.LookAt(target);
print ("I hit it");
}
}
Debug.DrawLine (ray2.origin, hit2.point, Color.green);
}
}
Comment
Answer by aldonaletto · Nov 05, 2011 at 03:20 AM
I didn't understand exactly what you're trying to do, but with a change in the ray creation you can click in the object and make it go in the target direction - but it will stop when you release the button, or when the object is no more under the mouse pointer:
function Update () { if(Input.GetButton("Fire1")) { var ray1 : Ray = camera.ScreenPointToRay (Input.mousePosition); var hit1 : RaycastHit; if (Physics.Raycast (ray1, hit1, 100)) { if(hit1.transform.tag == "Pullable") { hit1.transform.position = Vector3.MoveTowards(hit1.transform.position, target.position,Time.deltaTime * 25); hit1.transform.LookAt(target); } } Debug.DrawLine (ray1.origin, hit1.point, Color.red); } if(Input.GetButton("Fire2")) { var ray2 : Ray = camera.ScreenPointToRay (Input.mousePosition); var hit2 : RaycastHit; if (Physics.Raycast (ray2, hit2, 100)) { if(hit2.collider.gameObject.tag == "Teleport") { transform.position = Vector3.MoveTowards(transform.position, target1.position,Time.deltaTime * 25); transform.LookAt(target); print ("I hit it"); } } Debug.DrawLine (ray2.origin, hit2.point, Color.green); } }
Your answer
![](https://koobas.hobune.stream/wayback/20220613032642im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Raycast and Layer Masks 1 Answer
falling off 90 degree angles when walking on walls 0 Answers
How do I use raycast to simulate gun fire? 1 Answer
Unity3D raycast ignore self 3 Answers
Rotate to mouse seems to be inversed 1 Answer