Unity3d
From DreamsteepWiki
Contents |
RAYCASTING EXAMPLES
var prefabulous : Transform;
/************************/
//callback for raycast intersection
function rot_object ( hitobject,ray ) {
hitobject.transform.Rotate(0, 50*Time.deltaTime, 0);
light_pos = ray.GetPoint (60) ;
var temp_light =Instantiate( prefabulous ,light_pos ,Quaternion.identity); //transform.position
//instancebullet.rigidbody.AddForce(transform.forward * shootForce);
}
/************************/
function Update () {
//cast from an object and check to see what it is pointing at
/*
var fwd = transform.TransformDirection (Vector3.forward);
if (Physics.Raycast (transform.position, fwd, 10)) {
print ("There is something in front of the object!");
}
*/
//show the ray as a line - get info from object
/*
//Cast a ray cast and if an enemy is in front, it will lock onto them. Draws a line for reference.
var hit : RaycastHit;
if(Physics.Raycast (transform.position, transform.forward, hit, 100)
//&& hit.transform.gameObject.tag == "Enemy"){
){
Debug.DrawLine (transform.position, hit.point);
transform.LookAt(hit.transform);
}
*/
if(Input.GetMouseButton(0)) {
//tell me who I hit
var hit : RaycastHit;
var ray = Camera.main.ScreenPointToRay (Input.mousePosition);
var max_ray_length : float ;
max_ray_length = 100;
if (Physics.Raycast (ray,hit, max_ray_length)) {
//#WHAT OBJECT DID I HIT?
//print( hit.transform.gameObject );
//#SHOW ME SOME DATA ABOUT THE RAYCAST
//print (ray.origin);
//print (ray.direction);
//#SAMPLE A POINT ALONG THE VECTOR OF INTERSECTION
//print( ray.GetPoint (0) );
//print( ray.GetPoint (100) );
//#DRAW A LINE IN 3D REPRESENTING THE RAY
Debug.DrawLine (transform.position, hit.point);
//#GET SOME INFORMATION ABOUT THE OBJECT THAT IS HIT
//print( hit.transform.gameObject.transform.localPosition);
//print( hit.transform.gameObject.transform.childCount);
//#REACT IF CONDITIONS ARE MET
/*
if (hit.transform.gameObject.transform.childCount==1){
explode();
}*/
if (hit.transform.gameObject){
//print ('you hit object '+hit.transform.gameObject );
rot_object(hit.transform.gameObject,ray);
}//if object is intersecting the ray
}//if object is intersected from raycast
}//button click
}//end update
TRANSLATIONS IN 3D
General
Unity Specific
LANGUAGE TIPS
var target : Transform;
// Rotate the camera every frame so it keeps looking at the target
function Update() {
transform.LookAt(target);
}
Measure distance
function Update() {
if ( Vector3.Distance( enemy.position, transform.position ) < 10 )
print("I sense the enemy is near!");
}
variables
var test:float;
function Update () {
print (test);
test=test+1;
}
Objects
class MessagePlayerDie extends Message
{
function MessagePLayerDie()
{
super("player");
}
}
// Make the script also execute in edit mode.
@script ExecuteInEditMode()
// Just a simple script that looks at the target transform.
var target : Transform;
function Update () {
if (target)
transform.LookAt(target);
}
COMMON STUFF
function Update () {
if (Input.GetButtonDown("Jump"))
{
transform.position.z +=1.0;
}
}
EXIT
function OnGUI () {
if (GUI.Button (Rect (25, 25, 100, 30), "Quit")) {
Application.Quit();
}
}
function Update () {
transform.Rotate(0, 5*Time.deltaTime, 0);
transform.Translate(0, Time.deltaTime, 0);
}
EXAMPLE TOOLS
Shoot
var prefabBullet: Transform;
var shootForce: float ;
function Update () {
if(Input.GetButtonDown("Jump") )
{
var instancebullet =Instantiate( prefabBullet ,transform.position,Quaternion.identity);
instancebullet.rigidbody.AddForce(transform.forward * shootForce);
}
}
BUTTONS
function OnGUI () {
if (GUI.Button (Rect (100,10,150,100), "record")) {
print ("You clicked record!");
}
if (GUI.Button (Rect (0,10,150,100), "play")) {
print ("You clicked play!");
}
}
RBD Trigger
static var triggered=0;
function OnTriggerEnter (other : Collider) {
//print ("HIT!");
triggered=1;
}
function OnTriggerExit (other : Collider) {
//print ("fine ");
triggered=0;
}
DYNAMIC TEXT
function Update () {
var someNumber = groundtrigger.triggered;
var textt= someNumber.ToString();
guiText.text = textt; //typeof (groundtrigger.triggered);
}
FPS controller
private var motor : CharacterMotor;
// Use this for initialization
function Awake () {
motor = GetComponent(CharacterMotor);
}
// Update is called once per frame
function Update () {
// Get the input vector from kayboard or analog stick
var directionVector = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));
if (directionVector != Vector3.zero) {
// Get the length of the directon vector and then normalize it
// Dividing by the length is cheaper than normalizing when we already have the length anyway
var directionLength = directionVector.magnitude;
directionVector = directionVector / directionLength;
// Make sure the length is no bigger than 1
directionLength = Mathf.Min(1, directionLength);
// Make the input vector more sensitive towards the extremes and less sensitive in the middle
// This makes it easier to control slow speeds when using analog sticks
directionLength = directionLength * directionLength;
// Multiply the normalized direction vector by the modified length
directionVector = directionVector * directionLength;
}
// Apply the direction to the CharacterMotor
motor.inputMoveDirection = transform.rotation * directionVector;
motor.inputJump = Input.GetButton("Jump");
}
// Require a character controller to be attached to the same game object
@script RequireComponent (CharacterMotor)
@script AddComponentMenu ("Character/FPS Input Controller")
var width: float;
var height: float;
function Start() {
var verts: Vector3[] = new Vector3[4];
var normals: Vector3[] = new Vector3[4];
var uv: Vector2[] = new Vector2[4];
var tri: int[] = new int[6];
var mf: MeshFilter = GetComponent(MeshFilter);
verts[0] = new Vector3(0, 0, 0);
verts[1] = new Vector3(width, 0, 0);
verts[2] = new Vector3(0, 0, height);
verts[3] = new Vector3(width, 0, height);
for (i = 0; i < normals.Length; i++) {
normals[i] = Vector3.up;
}
uv[0] = new Vector2(0, 0);
uv[1] = new Vector2(1, 0);
uv[2] = new Vector2(0, 1);
uv[3] = new Vector2(1, 1);
tri[0] = 0;
tri[1] = 2;
tri[2] = 3;
tri[3] = 0;
tri[4] = 3;
tri[5] = 1;
var mesh: Mesh = new Mesh();
mesh.vertices = verts;
mesh.triangles = tri;
mesh.uv = uv;
mesh.normals = normals;
mf.mesh = mesh;
}
//FROM
//http://forum.unity3d.com/threads/19046-Read-Write-text-files-from-Unity-Webplayer
void Start () {
Debug.Log("Loader Script started");
string url = Application.dataPath + @"/Test.txt";
WWW request = new WWW(url);
while(!request.isDone) {
Debug.Log("Loading...");
}
Debug.Log("Data: " + request.data);
// Initialize the Game class
Game.Instance.Setup();
Application.LoadLevel(LevelToLoad);
}
//http://forum.unity3d.com/threads/45810-trigger-a-raycast-%28bullet%29
function Update () {
if (Input.GetButton ("Fire1")) {
var hit : RaycastHit;
if (Physics.Raycast (transform.position, transform.forward, hit, 1000) {
if (hit.gameObject.tag == "NPC") {
var damage = Random.Range (10,20);
BroadcastMessage ("ApplyDamage", damage);
}
}
}
}
Raycast shooting
//http://answers.unity3d.com/questions/4867/using-raycast-to-shoot
var par : ParticleEmitter;
var damage = 2;
function Update () {
var hit : RaycastHit;
// Use Screen.height because many functions (like this one) start in the bottom left of the screen, while MousePosition starts in the top left
var ray : Ray = Camera.main.ScreenPointToRay(Vector3(Input.MousePosition.x, Screen.height - Input.MousePosition.y,0));
if (Input.GetMouseButtonDown(0)) {
if (Physics.Raycast (ray, hit, 100, kDefaultRaycastLayers)) {
Instantiate(par, hit.point, Quaternion.LookRotation(hit.normal));
var otherObj : GameObject = hit.collider.gameObject;
if (otherObj.tag == "Enemy") {
otherObj.GetComponent(typeof(HealthAI)).CanDie(damage);
}
}
}
}
var aihitPoints : float = 10;
function CanDie ( damage : float) {
aihitPoints -= damage;
if(aihitPoints <= 0 ) {
Destroy(gameObject);
}
}
MACHINE GUN SCRIPT
//My First Unity tool , it will shooot stuff , Keith Legg Jan 24
//to use drag this script to the main camera (or a vehicle's transform node ) , then drag a prefab to the bullet channel on the right
//be sure to adjust force/rate of fire so bullets dont hit each other when instantiated (example: higher force = slower the rate)
//space bar will fire gun on positive Z axis
//for a good default try 1000 force , 3 shots , and .1 second delay
var bullet: Transform;
var shootForce: float ;
var fullauto: boolean = true;
var number_shots: int ;
var delay_shots: float ;
//"machine gun"
function shootfullauto () {
for (a=0;a<=number_shots;a++){
var instancedbullet =Instantiate( bullet ,transform.position,Quaternion.identity);
instancedbullet.rigidbody.AddForce(transform.forward * shootForce);
yield WaitForSeconds(delay_shots);
}
}
function Update () {
var timer : float = 0.0;
if (!fullauto){
if(Input.GetButtonDown("Jump") )
{
var instancebullet =Instantiate( bullet ,transform.position,Quaternion.identity);
instancebullet.rigidbody.AddForce(transform.forward * shootForce);
}
}
if (fullauto){
if(Input.GetButtonDown("Jump") )
{
shootfullauto();
}
}
}
A* (Untested)
//http://answers.unity3d.com/questions/12316/a-pathfinder-next-target
var target : Transform[];
var timer : float = 0.0;
var Rate : float = 1.0;
private var currentTarget: int;
function FixedUpdate () {
timer += Time.deltaTime;
if(timer > Rate){
this.GetComponent("Seeker").StartPath(transform.position,target[currentTarget].position);
timer = 0;
}
if(Vector3.Distance(transform.position,target[currentTarget].position)<=0){
currentTarget++;
if(currentTarget>=target.Length){
currentttarget = 0;
}
}
}
LINKS
http://unity3d.com/support/documentation/ScriptReference/ http://www.unifycommunity.com/wiki/index.php?title=Scripts http://www.unityprefabs.com/how-to-make-a-fps-game-tutorial.html#article http://infiniteunity3d.com/ http://www.youtube.com/watch?v=4IVxuXqFnCE&feature=player_embedded#!

