- Home /
Making shooting function with RayCast iPhone
I have a Player script that shoots a bullet (rigidBody) to kill an enemy, and the same for enemy, who shoots that same bullet to kill Player. Unfortunately enemy bullets mess with my camera ( it's a 3rd person camera) when they get between camera and Player, so the camera is jerking for like one frame.I took some examples from forum to replace bullets with raycast, but with no results. Is thers some simple way to replace my current functions of instantiating bulletPrefab with raycast?
Here I have 4 scripts:
Player script for Shooting:
#pragma strict #pragma implicit #pragma downcast
var groundSpeed : float; //Force applied when grounded var airSpeed : float; //Force applied when in air var jumpSpeed : float; //Force applied when jumping var touchHorizontalRotationSpeed : float; //Horizontal rotation speed of the player when using touch-joystick var mouseHorizontalRotationSpeed : float; //Horizontal rotation speed of the player when using the mouse var onGroundDrag : float; //Rigidbody drag used on ground var inAirDrag : float; //Rigidbody drag used in air var keyboardMouseEnabled : boolean; //Is keyboard and mouse used for moving and rotating the player, useful for Editor testing var movementJoystick : Joystick; //Joystick that controls the player movement var rotationJoystick : Joystick; //Joystick that controls the camera pivot rotation var bullitPrefab : GameObject; var target : playerMuzzleFlash;
private var onGround : boolean = false; //Determines whether the player is grounded or in air private var jump : boolean = false; //Determines whether the player should jump private var rb : Rigidbody; //Reference to the rigidbody component of the game object private var t : Transform; //Reference to the transform component of the game object
public var rayCastLength = 5; public var door1 : GameObject; public var door2 : GameObject; public var door3 : GameObject; public var door4 : GameObject; public var door5 : GameObject; public var door6 : GameObject; public var door7 : GameObject; public var door8 : GameObject; public var door9 : GameObject; public var doorStorage : GameObject;
function Awake() { rb = rigidbody; //Cache rigidbody component t = transform; //Cache transform component gameObject.layer = 8; //Set gameObject layer to Player layer }
//Check for one-off input in the Update loop since checking for input in FixedUpdate can lead to lost input events
function Update() {
var hit : RaycastHit;
if(Physics.Raycast(transform.position,transform.forward,hit,rayCastLength))
{
if (hit.collider.gameObject.tag =="door1")
{
openDoor1();
}
else if (hit.collider.gameObject.tag =="door2")
{
openDoor2();
}
else if (hit.collider.gameObject.tag =="door3")
{
openDoor3();
}
else if (hit.collider.gameObject.tag =="door4")
{
openDoor4();
}
else if (hit.collider.gameObject.tag =="door5")
{
openDoor5();
}
else if (hit.collider.gameObject.tag =="door6")
{
openDoor6();
}
else if (hit.collider.gameObject.tag =="door7")
{
openDoor7();
}
else if (hit.collider.gameObject.tag =="door8")
{
openDoor8();
}
else if (hit.collider.gameObject.tag =="door9")
{
openDoor9();
}
else if (hit.collider.gameObject.tag =="storageRoomDoor")
{
openDoorStorage();
}
}
//Since we're not applying rotation as torque, we don't need to do it in FixedUpdate
if(rotationJoystick) { //If rotation joystick exists
rb.MoveRotation(rb.rotation * Quaternion.Euler(Vector3.up * rotationJoystick.GetAxis().x * touchHorizontalRotationSpeed * Time.deltaTime)); //Rotate player using rotation joystick axis
}
if(keyboardMouseEnabled) { //If keyboard and mouse are enabled
rb.MoveRotation(rb.rotation * Quaternion.Euler(Vector3.up * Input.GetAxis("Mouse X") * mouseHorizontalRotationSpeed * Time.deltaTime)); //Rotate player using mouse axis
}
if(Input.GetKeyDown(KeyCode.Space) && keyboardMouseEnabled) { //If Space is hit and keyboard is enabled
Jump();
}
}
//Apply physics forces in FixedUpdate function FixedUpdate() { //Add force in the direction of movement var movement : Vector3; if(movementJoystick) { //If movement joystick exists movement = movementJoystick.GetAxis(); //Get movement joystick axis //Add force to player rigidbody using movement joystick axis rb.AddRelativeForce(movement.y Vector3.forward ((onGround) ? groundSpeed : airSpeed)); rb.AddRelativeForce(movement.x Vector3.right ((onGround) ? groundSpeed : airSpeed)); } if(keyboardMouseEnabled) { //If keyboard and mouse are enabled movement = Vector3(Input.GetAxisRaw("Horizontal"), Input.GetAxisRaw("Vertical"), 0); //Get keyboard movement axis if(movement.sqrMagnitude > 1) movement.Normalize(); //Add force to player rigidbody using keyboard axis rb.AddRelativeForce(movement.y Vector3.forward ((onGround) ? groundSpeed : airSpeed)); rb.AddRelativeForce(movement.x Vector3.right ((onGround) ? groundSpeed : airSpeed)); } if(jump) {
var bullit: GameObject = Instantiate(bullitPrefab, GameObject.Find("spawnPoint").transform.position,Quaternion.identity) as GameObject;
bullit.rigidbody.AddForce(transform.forward * 4000);
target.Flash();
}
if(jump) {
audio.Play();
}
if(jump) {
//rb.AddForce(t.up * jumpSpeed); //Add upwards force to make player jump
onGround = false; //Player is no longer grounded
jump = false;
rb.drag = inAirDrag; //Change rigidbody drag to allow for better movement in air
}
}
//If player is on ground, sets jump to true so player will jump when next FixedUpdate is called function Jump() { if(onGround) jump = true; }
//Check for collisions to determine when the player is on the ground function OnCollisionEnter(collision : Collision) { var collisionAngle = Vector3.Angle(collision.contacts[0].normal, Vector3.up); //Calculate angle between the up vector and the collision contact's normal if(collisionAngle < 40.0) { //If the angle difference is small enough, accept collision as hitting the ground onGround = true; //Player is grounded rb.drag = onGroundDrag; //Restore original drag value } }
function OnCollisionStay(collision : Collision) { var collisionAngle = Vector3.Angle(collision.contacts[0].normal, Vector3.up); //Calculate angle between the up vector and the collision contact's normal if(collisionAngle < 40.0) { //If the angle difference is small enough, accept collision as hitting the ground onGround = true; //Player is grounded rb.drag = onGroundDrag; //Restore original drag value } }
function OnCollisionExit (collision : Collision) { onGround = false; rb.drag = inAirDrag; }
function openDoor1(){
iTween.MoveTo(door1, {"x" : 16.2,"time" : 3, "transition" : "spring"});
yield WaitForSeconds (3);
iTween.MoveTo(door1, {"x" : 19.5, "time" : 3, "transition" : "spring"});
}
function openDoor2(){
iTween.MoveTo(door2, {"z" : 16.2, "time" : 3, "transition" : "spring"});
yield WaitForSeconds (3);
iTween.MoveTo(door2, {"z" : 19.5, "time" : 3, "transition" : "spring"});
}
function openDoor3(){
iTween.MoveTo(door3, {"x" : 37.7,"time" : 3, "transition" : "spring"});
yield WaitForSeconds (3);
iTween.MoveTo(door3, {"x" : 34.6,"time" : 3, "transition" : "spring"});
}
function openDoor4(){
iTween.MoveTo(door4, {"z" : 18.2, "time" : 3, "transition" : "spring"});
yield WaitForSeconds (3);
iTween.MoveTo(door4, {"z" : 14.9, "time" : 3, "transition" : "spring"});
}
function openDoor5(){
iTween.MoveTo(door5, {"z" : 16.2, "time" : 3, "transition" : "spring"});
yield WaitForSeconds (3);
iTween.MoveTo(door5, {"z" : 19.5, "time" : 3, "transition" : "spring"});
}
function openDoor6(){
iTween.MoveTo(door6, {"x" : 52.6,"time" : 3, "transition" : "spring"});
yield WaitForSeconds (3);
iTween.MoveTo(door6, {"x" : 49.4,"time" : 3, "transition" : "spring"});
}
function openDoor7(){
iTween.MoveTo(door7, {"z" : -21.4, "time" : 3, "transition" : "spring"});
yield WaitForSeconds (3);
iTween.MoveTo(door7, {"z" : -24.4, "time" : 3, "transition" : "spring"});
}
function openDoor8(){
iTween.MoveTo(door8, {"x" : 57.4, "time" : 3, "transition" : "spring"});
yield WaitForSeconds (3);
iTween.MoveTo(door8, {"x" : 54,"time" : 3, "transition" : "spring"});
}
function openDoor9(){
iTween.MoveTo(door9, {"x" : 86.9, "time" : 3, "transition" : "spring"});
yield WaitForSeconds (3);
iTween.MoveTo(door9, {"x" : 83.7,"time" : 3, "transition" : "spring"});
}
function openDoorStorage(){
iTween.MoveTo(doorStorage, {"x" : 21.4, "time" : 3, "transition" : "spring"});
yield WaitForSeconds (3);
iTween.MoveTo(doorStorage, {"x" : 24.45, "time" : 3, "transition" : "spring"});
}
function DisableRay(){
rayCastLength -= 5;
}
function EnableRay(){
rayCastLength += 5;
//iTween.MoveTo("Vector3": 1, "time" : 1);
}
Player script for lives:
using UnityEngine; using System.Collections;
public class PlayerLivesCollisions : MonoBehaviour { //Fields public int keyStatus = 0; public int lives = 100; public Texture2D h4; public Texture2D h3; public Texture2D h2; public Texture2D h1; public Texture2D h0; public Texture2D k1; public Texture2D k2; public Texture2D bag0; public Texture2D bag1; public Texture2D bag2; public Texture2D bag3; public Texture2D bag4; public Texture2D bag5; public int lvl; public int totalBags = 0; public int allBags; public int step; public GameObject goldExplode; //public GameObject modelis; //public GameObject blood; //public int timeNear = 0;
void OnGUI() { if(lives > 80){ GUI.Label (new Rect (820,10,220,40),h4); } else if(lives > 60){ GUI.Label (new Rect (820,10,220,40),h3); } else if(lives > 40){ GUI.Label (new Rect (820,10,220,40),h2); } else if(lives > 20){ GUI.Label (new Rect (820,10,220,40),h1); } else if(lives > 0){ GUI.Label (new Rect (820,10,220,40),h0); } if(keyStatus > 0){ GUI.Label (new Rect (700,25,64,64),k1); } if(keyStatus > 1){ GUI.Label (new Rect (700,25,64,64),k2); } if(totalBags < step){ GUI.Label (new Rect (130,5,45,50),bag0); } else if(totalBags == step){ GUI.Label (new Rect (130,5,45,50),bag1); } else if(totalBags == step 2){ GUI.Label (new Rect (130,5,45,50),bag2); } else if(totalBags == step*3){ GUI.Label (new Rect (130,5,45,50),bag3); } else if(totalBags == 4 step){ GUI.Label (new Rect (130,5,45,50),bag4); } else if(totalBags == 5 * step){ GUI.Label (new Rect (130,5,45,50),bag5); }
}
// void OnTriggerStay(Collider col)
// //{
// if (col. tag =="Enemy")
// timeNear++;
// if(timeNear>120)
// {
// lives--;
// timeNear = 0;
// }
// }
//Trigger Function
void OnTriggerEnter(Collider col)
{
if (col.tag == "bullet")
{
Debug.Log("Collision with Enemy detected");
//doDamage = true;
//Decrease Life and destroy bullet
lives -= 1;
//Destroy(col.gameObject);
}
else if (col.tag == "medKit")
{
if(lives <=75){
lives += 25;
Destroy(col.gameObject);
}
}
if (col.tag == "key1")
{
Debug.Log("man ir pirmaa atsleega");
gameObject.AddComponent("openSecurityRoomScene1");
//Decrease Life and destroy bullet
keyStatus += 1;
Destroy(col.gameObject);
}
else if (col.tag == "key2")
{
Debug.Log("man ir otraa atsleega");
gameObject.AddComponent("openExitScene1");
//Decrease Life and destroy bullet
keyStatus += 1;
Destroy(col.gameObject);
}
else if (col.tag == "bag")
{
totalBags += 1;
Destroy(col.gameObject);
Instantiate(goldExplode, transform.position,transform.rotation);
}
else if (col.tag == "LVLSwitcher")
{
if(allBags <= totalBags){
Application.LoadLevel(lvl);
}
}
//Check if we destroy our enemy
if (DidEnemyDie()){
//Destroy(modelis.gameObject);
//Instantiate(blood, transform.position, transform.rotation);
Application.LoadLevel(2);
//Destroy(gameObject);
}
}
//Function return true if life < 0
bool DidEnemyDie()
{
return lives <= 0 ? true : false;
}
}
Enemy Script for Shooting:
#pragma implicit // VARIABLES: ------------------------------------------------------------------ public var runSpeed : int; var bullitPrefab : GameObject; var maxDist = 5; var minDist = 50; var tick : int = 0; public var tickCount : int = 30; var target : muzzleFlash; var damp = 1.0; var play : Transform; //var target : GameObject.FindWithTag("PlayerTag");
// MOVING FUNCTION: ------------------------------------------------------------
function MoveEnemy(gotoPoint: Vector3) { // look at target defined: transform.LookAt(gotoPoint);
// get enemy controller:
var controller : CharacterController = GetComponent(CharacterController);
// set enemy moving towards player:
var moveDirection = transform.TransformDirection(Vector3.forward * runSpeed);
// set enemy gravity:
moveDirection.y = 8;
// move the enemy:
controller.SimpleMove(moveDirection);
}
// MAIN FUNCTION: --------------------------------------------------------------
function Update() { //var play = GameObject.FindWithTag("PlayerTag");
var rotate = Quaternion.LookRotation(play.position - transform.position);
transform.rotation = Quaternion.Slerp(transform.rotation, rotate, Time.deltaTime * damp);
//transform.LookAt(play.transform);
tick+=1;
var distance = Vector3.Distance(transform.position,GameObject.FindWithTag("PlayerTag").transform.position);
if (tick > tickCount){
Shoot();
tick = 0;
target.Flash();
}
if ( distance >= maxDist){
var pathComponent : Pathfinder = GetComponent(Pathfinder);
var gotoPoint : Vector3 = pathComponent.GetPath(GameObject.FindWithTag("PlayerTag"));
MoveEnemy(gotoPoint);
}
} function Shoot(){ var distance = Vector3.Distance(transform.position,GameObject.FindWithTag("PlayerTag").transform.position);
if ( distance <= minDist){
var bullit: GameObject = Instantiate(bullitPrefab, GameObject.Find("enemySpawnPoint").transform.position,Quaternion.identity) as GameObject;
bullit.rigidbody.AddForce(transform.forward * 4000);
audio.Play();
//yield WaitForSeconds(2);
}
}
// SCRIPT DEPENDENCES: ---------------------------------------------------------
@script RequireComponent(Pathfinder) @script RequireComponent(CharacterController)
Enemy Script for lives:
public var lives = 25; public var blood : GameObject; var t : MonoBehaviour; var message : String ;
function Start(){ var t = GameObject.FindWithTag("PlayerTag");
}
function Update (){ if(lives <=0){ dead = true;
Destroy(gameObject); Instantiate (blood, transform.position, transform.rotation);
t.Invoke(message, 0);
// iTweenEvent.GetEvent(GameObject.FindWithTag("PlayerTag"), "Shake").Play();
}
}
function OnTriggerEnter ( other : Collider){
if (other. tag == "bullet"){
lives -=1;
Destroy( other . gameObject);
}
}
//function getHit (){
//lives -= 1;
//}
Sorry, I know there are many other mistakes in my scripts...
Answer by Bunny83 · Apr 12, 2011 at 01:27 PM
Well, instant hit weapons work totally different. It's not that hard to do but in your case i think it would be easier to simply put the bullets on the "ignore raycast" layer. I don't know what you mean by "jerking" but i guess your camera uses a Raycast or Sphere-/Capsule-cast to detect obstacles behind the camera. So if a bullet "travels" through your view the camera would zoom in. If you set your bullet prefab layer to ignore raycast that should be fixed.
If you still want to convert your weapon into a instant hit weapon, well, just look around on this site, there are many examples for such a behaviour. I don't think anyone here will write the whole script for you ;)
Yes, you are right, by " jerking " I mean that camera zoom in for 1 frame... :) Great idea to put bullet prefab to ignore raycast layer, but it's not working, camera still is trying to zoom in...
Hmm, i don't know how your camera script works. It was just a guess (our cam works like this ;)) We actually used a seperate "Ignore Camera collision" layer that is ignored by the camera.