- Home /
Creating a teleportation gun
Hi, I've been trying to create a teleportation gun using raycasts and rigidbody's.
I have made a basic raycast gun
var bullet : Rigidbody;
var bulletPoint : Transform;
function Update ()
{
var hit : RaycastHit;
if (Input.GetButtonDown("Fire1"))
{
var fwd = transform.TransformDirection (Vector3.forward);
if (Physics.Raycast (transform.position, fwd))
print ("Raycast Hit!");
else
print ("Raycast Didn't Hit!");
var bulletInstance : Rigidbody;
bulletInstance = Instantiate(bullet, bulletPoint.position, bulletPoint.rotation); //Object to clone, origin of bullet, rotation
bulletInstance.AddForce(fwd * 500); //Moving projectile
Quaternion.LookRotation(hit.normal));
}
}
I also have a basic teleport script:
var target : Transform;
function Update () {
}
function OnTriggerEnter (col : Collider) {
if(col.gameObject.tag == "teleport") {
this.transform.position = target.position;
}
}
I'm trying to combine these two, so when the projectile hits a wall, it teleports the player to where it hit.
Any help is greatly appreciated.
well, thing is, this all looks fine except that when you add such a big force on 20th line the object will shoot so fast that unity may not be fast enough to detect the collision with the wall. I mean, in the first frame the object is in front of the wall, in the second it's already past the wall making unity think the collision never happened.
also, if your second script is attached to your hero, most probably nothing will happen because the OnTriggerEnter will check if the HERO is entering any trigger, but what you really need is to perform the same check in the bullet object. if the bullet hits the wall, take your hero and put it for the position of the bullet, destroy bullet.
Answer by Smithy311 · Dec 09, 2014 at 06:52 PM
I got it working!
Gun Script:
#pragma strict
var bullet : Rigidbody;
var bulletPoint : Transform;
var teleport;
function Update ()
{
var hit : RaycastHit;
if (Input.GetButtonDown("Fire1"))
{
var fwd = transform.TransformDirection (Vector3.forward);
if (Physics.Raycast (transform.position, fwd))//Check if raycast hit
print ("Raycast Hit!");
else
print ("Raycast Didn't Hit!");
var bulletInstance : Rigidbody;
bulletInstance = Instantiate(bullet, bulletPoint.position, bulletPoint.rotation); //Object to clone, origin of bullet, rotation
bulletInstance.AddForce(fwd * 500); //Moving projectile
//Destroy (bulletInstance.gameObject, 1);
//Quaternion.LookRotation(hit.normal);
}
}
Teleport Script:
var target : Transform;
var player : GameObject;
function OnTriggerEnter( col : Collider )
{
player = GameObject.Find("Player");
if(col.gameObject.tag == "teleport")
player.transform.position = target.position;
}
Your answer
Follow this Question
Related Questions
How to stop a rigidbody from bouncing off when colliding 2 Answers
Dragging object out of position 2 Answers
OnGUI nullreference 0 Answers
Detect Object that are hit by a ray 3 Answers
Need help with limiting rotation. 1 Answer