Showing posts with label Java Script. Show all posts
Showing posts with label Java Script. Show all posts

Thursday, June 30, 2011

Unity FPS Shooter Game Tutorial #4

Adding explosions to missiles that have been launched =====















as a reminder the projectile script is as below:

var explosion : GameObject;


function OnCollisionEnter( collision : Collision )
{
var contact : ContactPoint = collision.contacts[0];
var rotation = Quaternion.FromToRotation( Vector3.up, contact.normal );
var instantiatedExplosion : GameObject = Instantiate(
explosion, contact.point, rotation );
Destroy( gameObject );
}


Wednesday, June 29, 2011

Unity FPS Shooter Game Tutorial #3

Here is a modification in the launcher script to shoot two types of weapons
=================================================================================================================================================================================================================================

var projectile : Rigidbody;
var projectile2 : Rigidbody;
var speed = 20;

function Update () {


 if( Input.GetButtonDown( "Fire1" ) )
{

         var instantiatedProjectile : Rigidbody = Instantiate(
projectile, transform.position, transform.rotation );


instantiatedProjectile.velocity =
transform.TransformDirection( Vector3( 0, 0, speed ) );


   Physics.IgnoreCollision( instantiatedProjectile. collider,
     transform.root.collider );



}



if( Input.GetButtonDown( "Fire2" ) )
{

         var instantiatedProjectile2 : Rigidbody = Instantiate(
projectile2, transform.position, transform.rotation );


instantiatedProjectile2.velocity =
transform.TransformDirection( Vector3( 0, 0, speed ) );


   Physics.IgnoreCollision( instantiatedProjectile. collider,
     transform.root.collider );



}








}
==============================================================================================================================================================================================================================















Here is the two rigid bodies are a sphere (red sphere) and a cube(Xcube)

Unity FPS Shooter Game tutorial #2

Making the missile explode
======================================================================



var explosion : GameObject;
function OnCollisionEnter( collision : Collision )
{
 var contact : ContactPoint = collision.contacts[0];
 var rotation = Quaternion.FromToRotation( Vector3.up, contact.normal );
 var instantiatedExplosion : GameObject = Instantiate(
  explosion, contact.point, rotation );
 Destroy( gameObject );
}

========================================================================================================================================================

Finally,
we
 want 
to 
make
 the 
missile 
disappear 
from 
the
 game 
as 
it
 has 
now 
collided,

which 
is
 done 
by 
calling 
the 
Destroy()
 function 
with 
gameObject 
as 
a 
parameter

(gameObject 
denotes 
the
 object 
the 
script 
is 
associated
 with)


=====================================================================================================================================================


Add 
the
 code 
into 
the 
Projectile
 Javascript
 and
 save 
it.
Attach
 the
 Projectile
 Javascript 
to 
the
 Missile
 prefab 
by 
selecting
 Component
­>

Scripts
­>
Projectile.
Now 
we 
have 
to
 create 
the 
explosion 
that
 we
 want 
to 
occur
 when ever
 the
 missile 
col­
lides.
First,
create 
a
 new 
Prefab
 (call 
it 
Explosion)
 that 
will 
store 
the 
explosion 
asset.
The
 standard
 assets 
contain 
a 
nice 
explosion 
prefab 
with 
a 
particle
 system 
and 
a

light 
around 
the 
explosion.
Drag 
the 
explosion 
prefab 
under 
Standard
Assets/
Particles/explosion
 into 
the 
Hierarchy
 View.
Adjust
 the 
settings 
on 
the 
explosion 
until 
you’re 
happy 
with 
how 
it 
looks,
then

drag
 the 
Explosion 
from
 the 
Hierarchy 
view 
on to 
the 
Explosion 
Prefab
 in 
the

Project
 panel.
Now
 we 
can 
assign 
the 
explosion 
to 
the 
missile:
Ensuring
 that 
Missile 
prefab 
is 
selected,
 fill
 in 
the 
Explosion 
variable 
by 
dragging

the 
Explosion 
object 
in
 the 
Project 
panel 
onto
 the 
Missile’s
 Explosion 
variable
 in

the
 Inspector 
panel


Unity FPS Shooter Game tutorial


First we create an empty object called Launcher and then make it as a child of Main Camera and attach the script below to it  and give launcher an object that will be a  launched missile which has  to be a rigid body.
========================================================================

Here 
is  
the  
full  
code
  to
  MissileLauncher.js:
var projectile : Rigidbody;
var speed = 20;
function Update()
{
 if( Input.GetButtonDown( "Fire1" ) )
  {
  var instantiatedProjectile : Rigidbody = Instantiate(
   projectile, transform.position, transform.rotation );
  instantiatedProjectile.velocity =
   transform.TransformDirection( Vector3( 0, 0, speed ) );
  Physics.IgnoreCollision( instantiatedProjectile. collider,
   transform.root.collider );
  }
}


Tuesday, June 28, 2011

Instantiating Objects from an empty Game object



here is the script for the idea=========================================================================================================================================================================================================================

var object : Transform;




function Update () {

var theCloned : Transform;
theCloned = Instantiate(object,
transform.position, transform.rotation);




}
=============================================================================================================================================================================================================================

But here it is instantiating many Cubes that what we will change in the next script


Speed modeling for Cities in Games

 need to build a city level. With hi rise buildings, much of lites, etc. So, how is better to create buildings. To build each building in 3d tool, or create buildings from modules?

Little description. Buildings will be very hi. Like in "Blade Runner" or "Johnny Mnemonic". This is cyberpunk style, so you can imagine size of level and buildings. In some of them player can enter, and walk throw...




Idea#: I'd say write a script that generates the whole city from scratch. Mutch more interesting than spending hours building each building

the script will be creating buildings that are primitive Game objects 
============================================================================================================================================================================
Well, the fastest way, without using some sort of a script setup, is the block the whole city itself out with primative shapes, and then detail it down from there, you can decide what buildings are relevant enough that people will need to go inside them, and put interior stuff in those if thats how interactive it needs to be, otherwise just shape the outside of the city. By blocking it out first, you also insure the scale is how you want it
=========================================================================================================================================================================================================================================================



Getting animation to play all the way throughby pressing key once


I am trying to get an animation to play through all the way but it doesn't. The code I am using is:
function Update ()
 {
 if(Input.GetKeyDown("joystick button 2"))
 {
 animation.Play("HiroXAttack1");
 // name of the animation clip
 }
 }
======================================================================================================================================================

I have to press the button repeatedly to play the entire animation through.
I tried a different approach and did:
var isAttacking = false;
function Update ()
{
 if(Input.GetKeyDown("joystick button 2"))
 {
isAttacking = true;
 }
 if(isAttacking)
{
animation.Play("HiroXAttack1");
}

if(Input.anyKey == false)
{
 isAttacking = false;
 animation.Stop();
}
 }

=======================================================================================================================================================================

Your first code snippet should work, provided you have set your animation mode to Once, or Clamp, or ClampForever.
function Update ()
{
 if(Input.GetKeyDown("joystick button 2"))
 {
 animation.wrapMode = WrapMode.Once;
 animation.Play("HiroXAttack1");
// name of the animation clip
 }
}
==================================================================================================================================================

There is also a solution if you want the animations to be on the same layer. To play a given animation without stopping other animations on the same layer, you need to not use Animation.Play but instead do:
animation["MyOtherAnimation"].enabled = true;
animation["MyOtherAnimation"].weight = 1;
 animation["MyOtherAnimation"].time = 0;
==================================================================================================================================================


Lighting Idea=====> unity Game Idea

just like strategy games and some other games all places are dark and once you explore them the lights are turned on and you can see part of the map

=====================================================================================================================================================

psuedo code
====================================================================
function ontriggerenter()
{

  light.enabled=true;

}

How to play an animation all the way through on a single key


======================================================================================================================================================


var die1 : boolean;
var die2 : boolean; 
function Update() 
{
 if (Input.GetKeyDown(KeyCode.Alpha1))
 { die1 = true; 
die2 = false; 
} 
if (die1) 
{
 animation.CrossFade("die1"); 
animation.wrapMode = WrapMode.ClampForever; 
} 
if (Input.GetKeyDown(KeyCode.Alpha2)) 
{ die2 = true; die1 = false; }
 if (die2)
 { animation.CrossFade("die2"); 
animation.wrapMode = WrapMode.ClampForever; }
 else { 
animation.CrossFade("idle"); 
animation.wrapMode = WrapMode.Loop;
 } 
}

==================================================================================================================================================
if (die1) 
{
 if(animation.IsPlaying("die1"))
{ }
else
{
 animation.Play("die1"); 
} 
}
==================================================================================================================================================
the above code can be used to get an animation to play out fully without stopping on a single key press and even when you press the key again it shouldn't play, just double check that my "IsPlaying" method is used correctly

====================================================================================================================================================================
This seems to work just fine. Thank you all for your help.
==========================================================================================================================================================================================================================================================================================

function Start() 
{ 
animation["die1"].layer = 1; 
animation["die2"].layer = 1;
 } 
function Update() 
{ 
if (Mathf.Abs(Input.GetAxis("Vertical")) > 0.2)
 { 
animation.Stop("die1");
 animation.Stop("die2");
 if (Mathf.Abs(Input.GetAxis("Run")) > 0.2) 
{
 animation.CrossFade("run"); } 
else 
{ 
animation.CrossFade("walk");
 } } 
else if 
(Input.GetButton("Fire1"))
 {
 animation.Stop("die1");
 animation.Stop("die2"); 
animation["attack1"].wrapMode = WrapMode.Once; animation.Play("attack1"); 
} 
else if (Input.GetButton("Fire2")) 
{ 
animation.Stop("die1");
 animation.Stop("die2");
 animation["attack2"].wrapMode = WrapMode.Once;
 animation.Play("attack2"); 
} 

else if (Input.GetKeyDown(KeyCode.Alpha1)) 
{ 
animation["die1"].wrapMode = WrapMode.ClampForever; 
animation.CrossFade("die1"); 
} 
else if (Input.GetKeyDown(KeyCode.Alpha2))
 {
 animation["die2"].wrapMode = WrapMode.ClampForever; animation.CrossFade("die2"); 
} else { animation.CrossFade("idle"); 
}
 }
===========================================================================================================================================================

Play sound Once


To play a sound once during Update() use a boolean variable or instantiate a GameObject with an AudioSource with the same settings.
function Start() {
soundplayed = false;
 }

function Update ()
 {

 if (!soundplayed)
 {
  audio.PlayOneShot(blast);
  soundplayed = true;
 }
 ... }

how to make a animation play only when I get into the range of that game object?

 i have a game object that is an enemy. I want its animation to play only when I get really close to it.(im controllled by a fps player controller in my game) 



var rayCastLength = 5;
function Update () { var hit : RaycastHit;
//check if were in range... 
if(
Physics.Raycast(transform.position, transform.forward, hit, rayCastLength))
 { // ... 
with the object if(hit.collider.gameObject.tag == "lift_door") 
{
 //play the animation: hit.collider.gameObject.animation.Play("lift_door_open"); 
} 
}



}

Play animation and sound when GUI button is pressed



I have a GUI button that I have created. When the button is pressed I would like a game object to play a certain animation and also play a sound.
var lever : AudioClip;
if (GUI.Button (Rect(510,150,80,20), "Lever"))
 {
 animation.Play ("lever1"); 
audio.PlayOneShot(lever);
 }
=====================================================================================================================================================================
// Plays the default animation
animation.Play();
For a specific animation, you can call the animation with play as well.

// Plays the walk animation - stops all other animations in the same layer
animation.Play("walk");
// Plays the walk animation - stops all other animations
animation.Play("walk", PlayMode.StopAll);
====================================================================================================================================================================

AudioSource.PlayOneShot  

function PlayOneShot (clip : AudioClip, volumeScale : float = 1.0F) : void

Description

Plays an AudioClip.

// Play impact audio clip when colliding with something
var impact : AudioClip;
function OnCollisionEnter () {
audio.PlayOneShot(impact);
}

How to play entire animation?

how can i play entire animation when i hit an object or just simply pushing a button



For a button press


if(Input.GetButton("blah")){ do something;


or


if(Input.GetKey("a")){ do something;


OR

function OnControllerColliderHit(hit : ControllerColliderHit) 
{ 
 var player = GameObject.FindWithTag("w");

 if (hit.gameObject.tag =="w")
{
     player.animation.CrossFade("sit"); 
 }
 }

GameObject.CreatePrimitive




static function CreatePrimitive (type : PrimitiveType) : GameObject

Description

Creates a game object with a primitive mesh renderer and appropriate collider.

// Create a plane, sphere and cube in the scene.

function Start () {
var plane : GameObject = GameObject.CreatePrimitive(PrimitiveType.Plane);

var cube : GameObject = GameObject.CreatePrimitive(PrimitiveType.Cube);
cube.transform.position = Vector3(0, 0.5, 0);

var sphere : GameObject = GameObject.CreatePrimitive(PrimitiveType.Sphere);
sphere.transform.position = Vector3(0, 1.5, 0);

var capsule : GameObject = GameObject.CreatePrimitive(PrimitiveType.Capsule);
capsule.transform.position = Vector3(2, 1, 0);

var cylinder : GameObject = GameObject.CreatePrimitive(PrimitiveType.Cylinder);
cylinder.transform.position = Vector3(-2, 1, 0);
}

Monday, June 27, 2011

GUI Button Tricks


/* String Content example */

function OnGUI () {
GUI.Label (Rect (0,0,100,50), "This is the text string for a Label Control");
}
To display an image, declare a Texture2D public variable, and pass the variable name as the content argument like this:
/* Texture2D Content example */

var controlTexture : Texture2D;

function OnGUI () {
GUI.Label (Rect (0,0,100,50), controlTexture);
}
Here is an example closer to a real-world scenario:
/* Button Content examples */

var icon : Texture2D;

function OnGUI () {
if (GUI.Button (Rect (10,10, 100, 50), icon)) {
print ("you clicked the icon");
}

if (GUI.Button (Rect (10,70, 100, 20), "This is text")) {
print ("you clicked the text button");
}
}
There is a third option which allows you to display images and text together in a GUI Control. You can provide a GUIContent object as the Content argument, and define the string and image to be displayed within the GUIContent.
/* Using GUIContent to display an image and a string */

var icon : Texture2D;

function OnGUI () {
GUI.Box (Rect (10,10,100,50), GUIContent("This is text", icon));
}
You can also define a Tooltip in the GUIContent, and display it elsewhere in the GUI when the mouse hovers over it.
/* Using GUIContent to display a tooltip */

function OnGUI () {
// This line feeds "This is the tooltip" into GUI.tooltip
GUI.Button (Rect (10,10,100,20), GUIContent ("Click me", "This is the tooltip"));
// This line reads and displays the contents of GUI.tooltip
GUI.Label (Rect (10,40,100,20), GUI.tooltip);
}
If you're daring you can also use GUIContent to display a string, an icon, and a tooltip!
/* Using GUIContent to display an image, a string, and a tooltip */

var icon : Texture2D;

function OnGUI () {
GUI.Button (Rect (10,10,100,20), GUIContent ("Click me", icon, "This is the tooltip"));
GUI.Label (Rect (10,40,100,20), GUI.tooltip);
}

Random.Range (Random Variables)

Idea instantiating random fireworks in random places
=======================================================================================================================================================

Random.Range  

static function Range (min : float, max : float) : float

Description

Returns a random float number between and min [inclusive] and max [inclusive] (Read Only).
JavaScript
// Instantiates prefab somewhere between -10 and 10 on the x-z plane
var prefab : GameObject;
function Start () {
var position = Vector3(Random.Range(-10, 10), 0, Random.Range(-10, 10));
Instantiate(prefab, position, Quaternion.identity);
}

static function Range (min : int, max : int) : int

Description

Returns a random integer number between min [inclusive] and max [exclusive] (Read Only).
If max equals min, min will be returned. The returned value will never be max unless min equals max.

// Loads a random level from the level list

Application.LoadLevel(Random.Range(0, Application.levelCount));

Transform.LookAt (idea AI bots looking at player and shooting)

======================================================================================================================================================
// This complete script can be attached to a camera to make it
// continuously point at another object.

// The target variable shows up as a property in the inspector.
// Drag another object onto it to make the camera look at it.
var target : Transform;

// Rotate the camera every frame so it keeps looking at the target
function Update() {
transform.LookAt(target);
}

==================================================================================================================================================
// Point the object at the world origin
transform.LookAt(Vector3.zero);

Transform.RotateAround (Idea Orbiting around planets)


function RotateAround (point : Vector3, axis : Vector3, angle : float) : void

Description

Rotates the transform about axis passing through point in world coordinates by angle degrees.
This modifies both the position and the rotation of the transform.

function Update() {
// Spin the object around the world origin at 20 degrees/second.
transform.RotateAround (Vector3.zero, Vector3.up, 20 * Time.deltaTime);
}

Transform.Rotate Idea of instantiating rotating bullets with certain direction

function Update() {
// Slowly rotate the object around its X axis at 1 degree/second.
transform.Rotate(Vector3.right * Time.deltaTime);

// ... at the same time as spinning relative to the global
// Y axis at the same speed.
transform.Rotate(Vector3.up * Time.deltaTime, Space.World);
}



======================================================================================================================================================
function Update() {
// Slowly rotate the object around its X axis at 1 degree/second.
transform.Rotate(Time.deltaTime, 0, 0);

// ... at the same time as spinning it relative to the global
// Y axis at the same speed.
transform.Rotate(0, Time.deltaTime, 0, Space.World);
}

====================================================================================================================================================
function Update() {
// Slowly rotate the object around its X axis at 1 degree/second.
transform.Rotate(Vector3.right, Time.deltaTime);

// ... at the same time as spinning it relative to the global
// Y axis at the same speed.
transform.Rotate(Vector3.up, Time.deltaTime, Space.World);
}



==================================================================================================================================================

Transform.Translate Idea of Moving Platforms

=-========================================================================
Let's create some moving platforms that moves upward and then downward , also lets try moving platforms that moves forward and then backward
==========================================================================From the scripting manual
=========================================================================


function Update() {
// Move the object forward along its z axis 1 unit/second.
transform.Translate(Vector3.forward * Time.deltaTime);

// Move the object upward in world space 1 unit/second.
transform.Translate(Vector3.up * Time.deltaTime, Space.World);
}



==========================================================================
=======================================================================
function Update() {
// Move the object forward along its z axis 1 unit/second.
transform.Translate(0, 0, Time.deltaTime);

// Move the object upward in world space 1 unit/second.
transform.Translate(0, Time.deltaTime, 0, Space.World);
}

========================================================================
function Update() {
// Move the object to the right relative to the camera 1 unit/second.
transform.Translate(Vector3.right * Time.deltaTime, Camera.main.transform);
}

================================================================
function Update() {
// Move the object to the right relative to the camera 1 unit/second.
transform.Translate(Time.deltaTime, 0, 0, Camera.main.transform);
}