예제 #1
0
    protected override void ApplyEffect()
    {
        body = transform.parent.GetComponent<Rigidbody>();
        var v = body.velocity;

        var startNode = Grid.Instance.NodeFromWorldPoint(body.transform.position);
        int deltaX = 0;
        int deltaY = 0;
        if (Mathf.Abs(v.x) > Mathf.Abs(v.z))
            deltaX = v.x > 0 ? 1 : -1;
        else
            deltaY = v.z > 0 ? 1 : -1;

        int endX = startNode.gridX, endY = startNode.gridY;
        while (endX > 0 && endX < (Grid.Instance.gridSizeX - 1) && endY > 0 && endY < (Grid.Instance.gridSizeX - 1) && Grid.Instance.grid[endX, endY].walkable)
        {
            endX += deltaX;
            endY += deltaY;
        }
        endX -= deltaX;
        endY -= deltaY;
        endPos = Grid.Instance.grid[endX, endY].worldPosition;
        Debug.Log(startNode.worldPosition + " / " + v + "/" + endPos);

        body.GetComponent<Collider>().enabled = false;
        body.GetComponent<GridMovement>().Stop();
        body.GetComponent<GridMovement>().Freeze();
    }
 void OnTriggerEnter(Collider other)
 {
     if (other.GetComponent<Rigidbody> () != null) {
         player = other.gameObject.GetComponent<Rigidbody> ();
         bounceback = -player.velocity.y;
         Debug.Log (bounceback);
         player.velocity = new Vector3 (player.velocity.x, 0, 0);
         this.transform.localScale = compressedScale;
         framesTaken = 0;
         // Make it so hitting the trampoline can't kill the player
         if (player.name == "Character") {
             player.GetComponent<CharacterNavigate> ().previousVelocity = player.GetComponent<Rigidbody> ().velocity;
         }
     }
 }
예제 #3
0
 void shootAt(GameObject obj)
 {
     bullet = Instantiate (bulletPrefab, transform.position + Vector3.up, Quaternion.identity) as Rigidbody;
     BulletScript bulletScript = (BulletScript)bullet.GetComponent (typeof(BulletScript));
     bulletScript.damage = 10;
     bullet.AddForce (BallisticVel (obj.transform), ForceMode.Impulse);
 }
예제 #4
0
    void Grab(Rigidbody rb)
    {
        rb.isKinematic = false;
        isGrapped = true;
        rb.MovePosition(hand.transform.position);
        rb.velocity = Vector3.zero;
        hj.connectedBody = rb;

        rb.GetComponent<Item>().checkIfKaverit();
    }
예제 #5
0
    public void AttachToObject(Rigidbody rBody)
    {
        if(rBody == null)
        {
            isFixedToWorld = true;
            return;
        }

        RigidJoint joint = rBody.GetComponent<RigidJoint>() ?? rBody.gameObject.AddComponent<RigidJoint>();

        if (IsConnectedToJoint(joint.GetComponent<Rigidbody>())) return;

        attachedJoints.Add(joint);
    }
        void ApplyForceToTarget(Vector3 contactPoint, Rigidbody rb)
        {

            if ( rb.GetComponent<NavMeshAgent>() != null)
                rb.GetComponent<NavMeshAgent>().enabled = false;

            rb.isKinematic = false;

            if ( rb.CompareTag("Enemy") )
            {
                //rb.GetComponent<Rigidbody>().isKinematic = false;
                explosionPower = explosionPower * 10;
            }
              
            rb.AddExplosionForce(explosionPower, contactPoint, blastRadius, .5f, ForceMode.Impulse);
            //Vector3 direction = rb.transform.position - transform.position;
            //rb.AddForceAtPosition(direction.normalized, contactPoint, ForceMode.Impulse);

            if ( rb.CompareTag("Enemy") )
            {
                Destroy(rb.gameObject, destroyTime);
            }
        }
예제 #7
0
    private IEnumerator UnflipBody(Rigidbody body, Action callback)
    {
        float startTime = Time.time;

        while(BodyUneven(body))
        {
            body.GetComponent<PlayerHealth>().enabled = false;

            body.AddForce(Vector3.up * (4.0f - body.position.y) * 0.1f, ForceMode.VelocityChange);

            body.transform.rotation = Quaternion.Lerp(
                body.transform.rotation,
                Quaternion.identity,
                (Time.time - startTime) * 0.005f
                );

            yield return new WaitForFixedUpdate();
        }

        // Finished, call the callback
        callback();
        body.GetComponent<PlayerHealth>().enabled = true;
        body.isKinematic = false;
    }
예제 #8
0
    public PongBall(Rigidbody UnityBall,  Hashtable BallInfo)
    {
        this.actualBall = UnityBall;
        ballid = (string)BallInfo[FIELD_BALLID];
        this.actualBall.name = ballid;

        Hashtable vect = (Hashtable)BallInfo[FIELD_POSITION];
        position = PongSerializer.toVector(vect);
        actualBall.transform.position = position;

        vect = (Hashtable)BallInfo[FIELD_VELOCITY];
        velocity = PongSerializer.toVector(vect);
        actualBall.GetComponent<Rigidbody>().velocity = velocity;

        diameter = Convert.ToSingle((double)BallInfo[FIELD_DIAMETER]);
    }
예제 #9
0
    void Caminar(Rigidbody player, List<Vector2> listaCamino)
    {
        if (listaCamino.Count != 0 )
        {
            GetComponent<LineRenderer>().SetColors(Color.clear, Color.clear);
            Vector3 proximoPunto = new Vector3(listaCamino[0].x, 0, listaCamino[0].y);
            //Vector3 fwd = player.transform.TransformDirection(proximoPunto);
            player.GetComponent<Rigidbody>().transform.position = proximoPunto;

            if (!gameController.repetir)
            {
                listaBackUp.Add(listaCamino[0]);
            }

            listaCamino.Remove(listaCamino[0]);

            /* RaycastHit elrasho = new RaycastHit();
             if (listaCamino.Count != 0 && Physics.Raycast(player.position, fwd, out elrasho, Vector2.Distance(player.position, new Vector3(listaCamino[0].x, 0, listaDePuntos[0].y))))
             {
                 if (elrasho.collider.tag == "Enemy")
                 {
                     print("asdfasdfa");
                     gameController.finNivel = true;
                     repetir = false;
                     animacion = false;
                     //listaDePuntos.RemoveRange(0,listaDePuntos.Count);
                 }
             }
             */
        }
        else
        {
            if (gameController.palosGolf <= 1)
            {
                gameController.audioLose.Play();
                gameController.mensaje = "You didnt reach the goal!";
                gameController.finNivel = true;
            }
            else
            {
                gameController.palosGolf -= 1;
            }
        }
    }
예제 #10
0
 public bool braced(Rigidbody body, Vector3 dir)
 {
     RaycastHit hit;
     Rigidbody rigidTarg = body.GetComponent<Rigidbody>();
     if (Physics.Raycast (body.position, dir, out hit, .51f)) {
         Rigidbody rigidBrace = hit.collider.attachedRigidbody;
         Debug.DrawRay(body.position, dir,Color.yellow);
         if(rigidBrace == null)
         {
             Debug.Log ("no rigidbody.");
             return true;
         }
         if(rigidBrace.mass + rigidTarg.mass > 1.5*(rb.mass))
         {
             Debug.Log ("Braced");
             return true;
         }
     }
     Debug.Log ("Not braced");
     return false;
 }
예제 #11
0
    private void Awake()
    {
        cachedRigidbody = GetComponent<Rigidbody>();
        cachedCamera = GetComponentInChildren<Camera>();
        cachedPlayerCapsule = GetComponent<CapsuleCollider>();

        // create ghost player for jumping velocity
        var ghostPlayer = new GameObject("Ghost Player");
        ghostPlayer.AddComponent<CapsuleCollider>().height = cachedPlayerCapsule.height;
        ghostPlayerRB = ghostPlayer.AddComponent<Rigidbody>();
        ghostPlayer.transform.SetParent(transform);

        // set both of the capsule colliders to be similar
        cachedRigidbody.useGravity = ghostPlayerRB.useGravity = false;
        cachedRigidbody.constraints = ghostPlayerRB.constraints = RigidbodyConstraints.FreezeRotation;
        cachedRigidbody.interpolation = ghostPlayerRB.interpolation = RigidbodyInterpolation.Interpolate;
        cachedRigidbody.collisionDetectionMode = ghostPlayerRB.collisionDetectionMode = CollisionDetectionMode.Continuous;

        // adjust the camera height
        cachedCamera.transform.localPosition = new Vector3(0, 0.5f, 0);

        // make sure that the ghost collider doesn't interfere with the player collider
        Physics.IgnoreCollision(cachedPlayerCapsule, ghostPlayerRB.GetComponent<CapsuleCollider>());
    }
예제 #12
0
        public static void Store(Rigidbody rigidbody)
        {
            RigidbodySettingsHolder settingsHolder = rigidbody.GetComponent<RigidbodySettingsHolder>();
            if (settingsHolder == null)
            {
                settingsHolder = rigidbody.gameObject.AddComponent<RigidbodySettingsHolder>();
            }
            settingsHolder.Set(rigidbody);

            if (settingsHolder.settings.StoreCallback != null)
            {
                settingsHolder.settings.StoreCallback();
                settingsHolder.settings.StoreCallback = null;
            }
        }
예제 #13
0
 /// <summary>
 /// ReferencePoint 3D Constructor
 /// </summary>
 public ReferencePoint(Rigidbody body)
 {
     m_RigidBody3D = body;
     m_SphereCollider = body.GetComponent<SphereCollider>();
     m_Transform = body.transform;
     m_IsDummy = false;
 }
예제 #14
0
    void Update()
    {
        //If the player health is <= 0, destroy the player
        if(playerHealth <= 0.0f){
            if(playerIsAlive){ //Test to see if the player health has just crossed below 0.0

                centerMessageController.UpdateCenterMessage("Press Tab to Restart");
                centerMessageController.FlashCenterMessageAfterSeconds(0.5f);

                playerWeaponChange = playerGO.GetComponent<PlayerWeaponChange>();

                dropPoint = playerWeaponChange.dropPoint.position;
                //Test to see if the dropPoint is being blocked by an obstacle...
                RaycastHit wallHit;
                if(Physics.Raycast (playerWeaponChange.transform.position, (dropPoint - playerWeaponChange.transform.position), out wallHit, (dropPoint - playerWeaponChange.transform.position).magnitude, 1 << LayerMask.NameToLayer("Environment_Collision"))){
                    dropPoint = playerWeaponChange.transform.position+(wallHit.point-playerWeaponChange.transform.position)*0.8f;
                }

                usableWeapons = GameObject.FindGameObjectWithTag(Tags.gameController).GetComponent<UsableWeapons>();

                if(playerWeaponChange.hasPrimaryWeap == true){
                    string equippedWeaponName = playerWeaponChange.primaryEquipped.gameObject.GetComponent<weaponIndex> ().weaponName;
                    int equippedWeaponIndex = usableWeapons.primaryUsableWeapons.IndexOf (equippedWeaponName);
                    dropWeapon = Instantiate(usableWeapons.worldPrimaryUsableWeapons [equippedWeaponIndex], dropPoint, playerWeaponChange.primarySpawnpoint.rotation) as Rigidbody;
                    dropWeapon.AddForce(playerGO.GetComponent<Rigidbody>().velocity*playerWeaponChange.dropForce);
                    dropWeapon.AddTorque (transform.up*playerWeaponChange.dropForce*Random.Range(-0.5f, 0.5f));
                    dropWeapon.GetComponent<weaponIndex>().ammoCount = playerWeaponChange.primaryEquipped.gameObject.GetComponent<weaponIndex> ().ammoCount;
                }
                if(playerWeaponChange.hasSecondaryWeap == true){
                    string equippedWeaponName = playerWeaponChange.secondaryEquipped.gameObject.GetComponent<weaponIndex> ().weaponName;
                    int equippedWeaponIndex = usableWeapons.secondaryUsableWeapons.IndexOf (equippedWeaponName);
                    dropWeapon = Instantiate(usableWeapons.worldSecondaryUsableWeapons [equippedWeaponIndex], dropPoint, playerWeaponChange.secondarySpawnpoint.rotation) as Rigidbody;
                    dropWeapon.AddForce(playerGO.GetComponent<Rigidbody>().velocity*playerWeaponChange.dropForce);
                    dropWeapon.AddTorque (transform.up*playerWeaponChange.dropForce*Random.Range(-0.5f, 0.5f));
                    dropWeapon.GetComponent<weaponIndex>().ammoCount = playerWeaponChange.secondaryEquipped.gameObject.GetComponent<weaponIndex> ().ammoCount;
                }
                deadBody = Instantiate (deadPlayer[damageTypeIndex], playerGO.transform.position, playerWeaponChange.primarySpawnpoint.rotation) as Rigidbody;

                //Check for helmet...
                if(deadBody.GetComponent<Animator>()){
                    Animator[] anims = playerGO.GetComponentsInChildren<Animator> ();
                    Animator deadBodyAnim = deadBody.GetComponent<Animator>();
                    foreach (Animator a in anims) {
                        AnimatorControllerParameter[] acps = a.parameters;
                        foreach (AnimatorControllerParameter acp in acps){
                            if(acp.name == "helmetEquipped"){
                                bool currentValue = a.GetBool ("helmetEquipped");
                                deadBodyAnim.SetBool ("helmetEquipped", currentValue);
                                break;
                            }
                        }
                    }
                    AnimatorControllerParameter[] deadBodyAcp = deadBodyAnim.parameters;
                    AnimatorControllerParameterType paramType = AnimatorControllerParameterType.Bool;
                    int randomIndex = 0;
                    while (paramType != AnimatorControllerParameterType.Trigger){
                        randomIndex = Random.Range (0, deadBodyAcp.Length); //Random.Range is exclusive for the 2nd value
                        paramType = deadBodyAcp[randomIndex].type;
                    }
                    deadBodyAnim.SetTrigger (deadBodyAcp [randomIndex].name);
                }
                //End check for helmet

                if(damageForce != Vector3.zero){
                    deadBody.AddForce (damageForce);
                }
                if(explosionForce != 0.0f){
                    //deadBody.AddExplosionForce(explosionForce, explosionLocation, explosionRadius);
                    deadBody.AddForce (explosionForce*((playerGO.transform.position - explosionLocation).normalized));
                }
            }
            playerIsAlive = false;
            Destroy(playerGO);

        }
    }
예제 #15
0
 private void Recoil(Rigidbody ApplyForceTo, Vector3 AtPosition)
 {
     ApplyForceTo.GetComponent<Rigidbody>().AddForceAtPosition(-this.transform.up * recoilFactor , AtPosition);
 }
예제 #16
0
	public void StartMovements() {
		ivr = this.GetComponent<InstantVR>();

		headTarget = ivr.headTarget;
		leftHandTarget = ivr.leftHandTarget;
		rightHandTarget = ivr.rightHandTarget;
		hipTarget = ivr.hipTarget;
		leftFootTarget = ivr.leftFootTarget;
		rightFootTarget = ivr.rightFootTarget;

		animator = ivr.transform.GetComponentInChildren<Animator>();
        if (animator == null) {
            StopMovements();
        } else {

            characterRigidbody = animator.GetComponent<Rigidbody>();

            if (characterRigidbody != null)
                characterTransform = characterRigidbody.GetComponent<Transform>();

            if (leftArm == null)
                leftArm = new ArmMovements(ivr, ArmMovements.BodySide.Left, this);
            leftArm.Initialize(ivr, ArmMovements.BodySide.Left, this);

            if (rightArm == null)
                rightArm = new ArmMovements(ivr, ArmMovements.BodySide.Right, this);
            rightArm.Initialize(ivr, ArmMovements.BodySide.Right, this);

            Transform neck, spine, hips;

            neck = animator.GetBoneTransform(HumanBodyBones.Neck);
            if (neck == null)
                neck = animator.GetBoneTransform(HumanBodyBones.Head);
            spine = animator.GetBoneTransform(HumanBodyBones.Spine);
            hips = animator.GetBoneTransform(HumanBodyBones.Hips);
            torso = new Torso(neck, spine, hips, hipTarget, headTarget, rightArm);

            leftLeg = new Leg(ArmMovements.BodySide.Left, animator, hipTarget);
            rightLeg = new Leg(ArmMovements.BodySide.Right, animator, hipTarget);

            if (rightHandTarget != null) {
                rightHandOTarget = rightHandTarget;
                /*
                float targetScaleZ = rightHandTarget.transform.localScale.z;
                rightPalmTarget = new GameObject();
                rightPalmTarget.name = "Palm_R_Target";
                rightPalmTarget.transform.parent = rightHandTarget.transform;
                rightPalmTarget.transform.localPosition = new Vector3(0, 0, -palmLength/targetScaleZ);
                rightPalmTarget.transform.localEulerAngles = Vector3.zero;
				
                rightHandTarget = rightPalmTarget.transform;
                */
            }

            if (leftHandTarget != null) {
                leftHandOTarget = leftHandTarget;
                /*
                float targetScaleZ = leftHandTarget.transform.localScale.z;
                leftPalmTarget = new GameObject();
                leftPalmTarget.name = "Palm_L_Target";
                leftPalmTarget.transform.parent = leftHandTarget.transform;
                leftPalmTarget.transform.localPosition = new Vector3(0, 0, -palmLength/targetScaleZ);
                leftPalmTarget.transform.localEulerAngles = Vector3.zero;

                leftHandTarget = leftPalmTarget.transform;
                */
            }

            if (headTarget == null && enableTorso) {
                GameObject neckTargetGO = new GameObject("Neck_Target");
                headTarget = neckTargetGO.transform;
                headTarget.parent = characterTransform;
                headTarget.position = torso.neck.position;
                headTarget.rotation = characterTransform.rotation;
            }

            if (enableLegs) {
                if (rightFootTarget == null) {
                    //userLegTargets = false;
                    GameObject rightFootTargetGO = new GameObject("Foot_R_Target");
                    rightFootTarget = rightFootTargetGO.transform;
                    rightFootTarget.parent = characterTransform;
                    rightFootTarget.position = rightLeg.foot.position;
                    rightFootTarget.rotation = characterTransform.rotation;
                }

                if (leftFootTarget == null) {
                    //userLegTargets = false;
                    GameObject leftFootTargetGO = new GameObject("Foot_L_Target");
                    leftFootTarget = leftFootTargetGO.transform;
                    leftFootTarget.parent = characterTransform;
                    leftFootTarget.position = leftLeg.foot.position;
                    leftFootTarget.rotation = characterTransform.rotation;
                }
            }


            if (IsInTPose(leftArm, rightArm)) {
                CalculateFromNormTPose(leftArm, rightArm);
            } else {
                CalculateFromNormTracking(leftArm, rightArm, leftHandTarget, rightHandTarget);
            }
        }
    }
예제 #17
0
	//called when object other enters your collider
	public void SetActive(Rigidbody other) {
		if (activeObj == other || grabbing) //don't reactivate same object. Grabbing locks active object.
			return;
		if (activeObj != null) {
			SetInactive (activeObj);
		}
		activeObj = other;
		MeshRenderer mr = other.GetComponent<MeshRenderer>();
		if ( mr ) {
			oldMats = mr.materials;
			Material[] mats = new Material[mr.materials.Length];
			for (int i = 0; i < mats.Length; i++) {
				mats [i] = outlineMat;
				mats [i].mainTexture = mr.materials [i].mainTexture;
			}
			mr.materials = mats;
		}
	}
예제 #18
0
    // Update is called once per frame
    void Update()
    {
        if (cursorShouldBeLocked)
        {
            Cursor.lockState = CursorLockMode.Locked;
            Cursor.visible = false;
        }
        else
        {
            Cursor.lockState = CursorLockMode.None;
            Cursor.visible = true;
        }
        if (holderActive)
        {
            rocketHolder = new Vector3(instanciateProjectilerocketBall.position.x, instanciateProjectilerocketBall.position.y, instanciateProjectilerocketBall.position.z);
            despawnTick += Time.deltaTime;
            if (despawnTimer < despawnTick )
            {
                despawnTick = 0;
                holderActive = false;
            }

        }
        if (LAUNCH)
        {
            missileTick += Time.deltaTime;
            if (missileTick > missileDelay + 0.5)
            {
                for (int i = 0; i < launcherRows; i++)
                {
                    for (int j = 0; j < launcherCol; j++)
                    {
                        instanciateProjectileRocket = Instantiate(rocket, rocketHolder, transform.rotation) as Rigidbody;
                        instanciateProjectileRocket.GetComponent<Rigidbody>().AddForce(Random.insideUnitSphere * 50.0f);
                        Destroy(instanciateProjectileRocket.gameObject, 10f);
                        //instanciateProjectileRocket.velocity = transform.TransformDirection(new Vector3(rocketBallX, rocketBallY, rocketBallZ));
                    }
                }
                LAUNCH = false;
                missileTick = 0;
            }
        }
        if (Input.GetButtonDown("Fire1"))
        {
            StopCoroutine("Paint");
            StartCoroutine("Paint");
        }
    }
예제 #19
0
	//Called when object leaves collider
	public void SetInactive(Rigidbody other) {
		if (activeObj == other && !grabbing) { //don't let go if you turn quickly while grabbing
			activeObj = null;
			MeshRenderer mr = other.GetComponent<MeshRenderer> ();
			if (mr) {
				mr.materials = oldMats;
				oldMats = null; 
			}
		}
	}
예제 #20
0
    // Use this for initialization
    void Start()
    {
        /******************************************************************************
        * Instanciation de tous les éléments de la scène, taille et position variant
        * 							selon le fichier de données
        *******************************************************************************/

        //Instanciation de la gare, changement de la taille en fonction des données
        largRect = Display.initDimReseau_Rect(textFileUser);

        Rigidbody cubeGare0 = Instantiate(cubeGare);
        cubeGare0.transform.localScale = new Vector3(largRect, 1, zScaleCube);
        cubeGare0.isKinematic = true; //disable physics on cube
        xCube0 = xLM1;
        yCube0 = yLM1;
        zCube0 = largRect/2;
        cubeGare0.transform.position = new Vector3(xCube0, yCube0, zCube0);
        Rigidbody cubeGare1 = Instantiate(cubeGare);
        cubeGare1.transform.localScale = new Vector3(largRect, 1, zScaleCube);
        cubeGare1.isKinematic = true; //disable physics on cube
        xCube1 = (largRect/2.0f)- (zScaleCube/2.0f);
        yCube1 = yCube0;
        zCube1 = largRect+0.5f;
        cubeGare1.transform.Rotate(Vector3.up, 90, Space.Self);
        cubeGare1.transform.position = new Vector3(xCube1, yCube1, zCube1);
        Rigidbody cubeGare2 = Instantiate(cubeGare);
        cubeGare2.transform.localScale = new Vector3(largRect, 1, zScaleCube);
        cubeGare2.isKinematic = true; //disable physics on cube
        xCube2 = largRect;
        yCube2 = yCube1;
        zCube2 = (largRect/2)+zScaleCube;
        cubeGare2.transform.position = new Vector3(xCube2, yCube2, zCube2);
        Rigidbody cubeGare3 = Instantiate(cubeGare);
        cubeGare3.transform.localScale = new Vector3(largRect, 1, zScaleCube);
        cubeGare3.isKinematic = true; //disable physics on cube
        xCube3 = (largRect/2.0f)+1;
        yCube3 = yCube1;
        zCube3 = zScaleCube/4.0f;;
        cubeGare3.transform.Rotate(Vector3.up, 90, Space.Self);
        cubeGare3.transform.position = new Vector3(xCube3, yCube3, zCube3);

        //Instanciation des 4 repères aux quatre coins de la structure
        Rigidbody landmark1 = Instantiate(Landmark);
        landmark1.transform.position = new Vector3(xLM1, yLM1+1, zLM1);
        landmark1.isKinematic = true;
        Rigidbody landmark2 = Instantiate(Landmark);
        zLM2 = largRect +0.5f;
        landmark2.transform.position = new Vector3(xLM2, yLM2, zLM2);
        landmark2.isKinematic = true;
        Rigidbody landmark3 = Instantiate(Landmark);
        xLM3 = largRect;
        zLM3 = largRect + 0.5f;
        landmark3.transform.position = new Vector3(xLM3, yLM3, zLM3);
        landmark3.isKinematic = true;
        Rigidbody landmark4 = Instantiate(Landmark);
        xLM4 = largRect;
        zLM4 = 0.5f;
        landmark4.transform.position = new Vector3(xLM4, yLM4, zLM4);
        landmark4.isKinematic = true;

        //Instanciation de la porte et de la minimap caméra
        Rigidbody checkDoor = Instantiate(door);
        checkDoor.transform.localScale = new Vector3(6, 0.9f, 1.8f);
        xDoor = xCube0;
        yDoor = yCube0+3.05f;
        zDoor = largRect/2.0f;
        checkDoor.transform.position = new Vector3(xDoor, yDoor, zDoor);
        checkDoor.isKinematic = true;
        boxCollDoor = checkDoor.GetComponent<BoxCollider>(); //doit accéder au boxCollider pour pouvoir en faire un trigger
        boxCollDoor.isTrigger =true;
        Camera secondViewCam = Instantiate(secondCam);
        xSecCam = xDoor+6f;
        ySecCam = yDoor+8f;
        zSecCam = zDoor+0.5f;
        secondViewCam.transform.position = new Vector3(xSecCam, ySecCam, zSecCam);
        secondViewCam.transform.Rotate(80, 90, 0);
        secondViewCam.clearFlags = CameraClearFlags.SolidColor;
        secondViewCam.orthographic = true;
        secondViewCam.orthographicSize = 9;
        secondViewCam.rect = new Rect(-.5f, 0.7f, 0.75f, 0.3f);

        //Postionnement de départ des trains
        firstTrain = Instantiate(Train1);
        xTrain1 = xLM1;
        yTrain1 = yLM1;
        zTrain1 = (largRect/3.0f)+yTrain1;
        firstTrain.transform.position = new Vector3(xTrain1,yTrain1, zTrain1);
        firstTrain.isKinematic = true;
        secondTrain = Instantiate(Train2);
        xTrain2 = xTrain1;
        yTrain2 = yTrain1;
        zTrain2 = zScaleCube*2;
        secondTrain.transform.position = new Vector3(xTrain2,yTrain2, zTrain2);
        secondTrain.isKinematic = true;

        /*Positionnement de la caméra en fonction de la position du repère et enlever
        le GUILayer (pour éviter que les infos soient visibles partout)*/
        goCam = GameObject.Find("Main Camera");
        rbCam = goCam.GetComponent<Rigidbody>();
        xCam = xLM1-9f;
        yCam = largRect-zScaleCube/2;
        zCam = zLM1 - ((largRect/3)+zScaleCube)+.5f;
        rbCam.transform.position = new Vector3(xCam, yCam, zCam);
        Vector3 axisCamera = new Vector3(51,40,10);
        rbCam.transform.rotation = Quaternion.Euler(axisCamera);
        GUILayer guilayer = rbCam.GetComponent<GUILayer>();
        guilayer.enabled = false;

        //Positionnement de l'éclairage en fonction de la position du repère
        goLight = GameObject.Find("MainLight");
        rbLight = goLight.GetComponent<Rigidbody>();
        xLight = largRect;
        yLight = largRect;
        zLight = zLM1;
        rbLight.transform.position = new Vector3(xLight, yLight, zLight);

        //Instanciation et positionnement du panneau d'affichage et de sa camera
        screenBd = Instantiate (ScreenBoard);
        xScreen = xLM1 + 5.6f;
        yScreen = xLM1 + 11f;
        zScreen = zLM1 + 20.5f;
        screenBd.transform.position = new Vector3(xScreen, yScreen, zScreen);
        Camera screenViewCam = Instantiate(ScreenViewCamera);
        xScreenCam = xLM1 +5.6f;
        yScreenCam = yLM1 + 12f;
        zScreenCam = zLM1 + 3.36f;
        screenViewCam.transform.position = new Vector3(xScreenCam, yScreenCam, zScreenCam);

        //Contenu du panneau d'affichage
        GUIText t1Txt = Instantiate(textScreen);
        t1Txt.text = "Train 1";
        t1Txt.transform.position = new Vector3(0.72f,0.90f, 21f);
        xCoordT1 = Instantiate(textScreen);
        xCoordT1.transform.position = new Vector3(0.72f,0.75f, 21f);
        yCoordT1 = Instantiate(textScreen);
        yCoordT1.transform.position = new Vector3(0.72f,0.6f, 21f);
        zCoordT1 = Instantiate (textScreen);
        zCoordT1.transform.position = new Vector3(0.72f,0.45f, 21f);
        GUIText t2Txt = Instantiate(textScreen);
        t2Txt.text = "Train 2";
        t2Txt.transform.position = new Vector3(0.84f,0.90f, 21f);
        xCoordT2 = Instantiate(textScreen);
        xCoordT2.transform.position = new Vector3(0.85f,0.75f, 21f);
        yCoordT2 = Instantiate(textScreen);
        yCoordT2.transform.position = new Vector3(0.85f,0.6f, 21f);
        zCoordT2 = Instantiate (textScreen);
        zCoordT2.transform.position = new Vector3(0.85f,0.45f, 21f);
        GUIText collisionText = Instantiate(textScreen);
        collisionText.text = "Collisions évitées :";
        collisions = Instantiate(textScreen);
        collisions.transform.position = new Vector3(0.5f, 0.9f, 0);
        GUIText nombrePositionsText = Instantiate(textScreen);
        nombrePositionsText.text = "Changements de positions: ";
        nombrePositionsText.transform.position = new Vector3(0.28f, 0.67f, 0);
        positionsChange = Instantiate (textScreen);
        positionsChange.transform.position = new Vector3(0.59f, 0.67f ,0);
        GUIText tauxErreurText = Instantiate(textScreen);
        tauxErreurText.text = "Taux d'erreurs: ";
        tauxErreurText.transform.position = new Vector3(0.28f, 0.26f, 0);
        tauxErreurText.fontSize = 28;
        tauxErreurText.fontStyle = FontStyle.Bold;
        tauxErreur = Instantiate(textScreen);
        tauxErreur.transform.position = new Vector3(0.56f, 0.26f, 0);
        tauxErreur.fontSize = 26;
        tauxErreur.color = Color.red;
        tauxErreur.fontStyle = FontStyle.Bold;
        GUIText nomApp = Instantiate(textScreen);
        nomApp.text = "Train Station";
        nomApp.transform.position = new Vector3(0.05f, 0.9f, 0);
        nomApp.fontSize = 25;
        nomApp.fontStyle = FontStyle.Bold;
        nomApp.color = Color.red;

        noLoc = Display.howManyLocation(textFileUser);//compte le nombre de lignes dans le fichier de données
    }
예제 #21
0
        public static void Restore(Rigidbody rigidbody)
        {
            RigidbodySettingsHolder settingsHolder = rigidbody.GetComponent<RigidbodySettingsHolder>();
            if (settingsHolder != null)
            {
                rigidbody.isKinematic = settingsHolder.settings.isKinematic;
                rigidbody.velocity = settingsHolder.settings.velocity;
                rigidbody.angularVelocity = settingsHolder.settings.angularVelocity;
                rigidbody.mass = settingsHolder.settings.mass;
                rigidbody.drag = settingsHolder.settings.drag;
                rigidbody.angularDrag = settingsHolder.settings.angularDrag;
                rigidbody.useGravity = settingsHolder.settings.useGravity;
                rigidbody.interpolation = settingsHolder.settings.interpolate;
                rigidbody.collisionDetectionMode = settingsHolder.settings.collisionDetection;
                rigidbody.constraints = settingsHolder.settings.constraints;
                Object.Destroy(settingsHolder);

                if (settingsHolder.settings.RestoreCallback != null)
                {
                    settingsHolder.settings.RestoreCallback();
                    settingsHolder.settings.RestoreCallback = null;
                }
            }
            else
                Debug.LogError("Cannot restore rigidbody (" + rigidbody.name + ")! No settings holder found");
        }
예제 #22
0
    public Body AddBodyToLeapFromUnity(Rigidbody rigidbody)
    {
      LeapInteraction properties = rigidbody.GetComponent<LeapInteraction>();

      if (rigidbody.collider && properties)
      {
        Collider[] colliders = rigidbody.GetComponents<Collider>();
        
        Shape shape = new Shape();
        foreach(Collider collider in colliders)
        {
          if (collider is SphereCollider)
          {
            float scale = rigidbody.transform.lossyScale.x;
            SphereCollider sc = collider as SphereCollider;
            shape = Shape.CreateSphere(sc.radius * scale);
          }
          else if (collider is CapsuleCollider)
          {
            float scale = rigidbody.transform.lossyScale.x;
            CapsuleCollider cc = collider as CapsuleCollider;
            shape = Shape.CreateCapsule((Shape.CapsuleOrientation)cc.direction, Math.Max(0f, cc.height / 2f - cc.radius) * scale, cc.radius * scale);
          }
          else if (collider is BoxCollider)
          {
            BoxCollider bc = collider as BoxCollider;
            Vector3 scale = collider.transform.lossyScale;
            shape = Shape.CreateBox(Vector3.Scale(bc.size, scale) / 2f, 0f);
          }
        }
        
        if (shape != IntPtr.Zero)
        {
          Body body = new Body();//shape);
          body.Shape = shape;
          body.Mass = rigidbody.mass;
          
          // Add body anchors.
          for (int i = 0; i < rigidbody.transform.childCount; i++)
          {
            Transform child = rigidbody.transform.GetChild(i);
            if (child.name.StartsWith("Anchor") || child.name.StartsWith("ClickAnchor"))
            {
              LeapTransform anchor = new LeapTransform();
              anchor.Position = Vector3.Scale(child.localPosition - rigidbody.transform.rotation * TransformSyncUtil.GetCenterFromCollider(rigidbody.gameObject), rigidbody.transform.lossyScale);
              anchor.Rotation = child.localRotation;
              if (child.name.StartsWith("Anchor")) { body.Shape.AddAnchor(anchor); }
              if (child.name.StartsWith("ClickAnchor")) 
              {
                body.Shape.AddClickAnchor(anchor); 
              }
            }
          }
          
          // Apply BodyProperties
          properties.ApplyToBody(body);

          Scene.AddBody(body);
          BodyMapper.Add(rigidbody.gameObject, body);

          rigidbody.maxAngularVelocity = 100.0f;

          return body;
        }
      }
      return null;
    }
예제 #23
0
    void Update()
    {
        facingDirection = script.GetFacingDirection ();

        // Throw Shuriken left or right
        if (amountUsed < 4) {
            if (Input.GetKeyDown (KeyCode.I)) {
                Clone = Instantiate (ShurikenPrefab, new Vector3 (spawnThrow.transform.position.x, spawnThrow.transform.position.y, -3.0f),
                                     	  Quaternion.identity) as Rigidbody;
                textObject = Instantiate (TextControlPrefab,
                                          new Vector3 (Clone.transform.position.x - 0.414f, Clone.transform.position.y + 0.352f, -3.0f),
                                          Quaternion.identity) as GameObject;

                // get first open slot
                for (int i = 0; i < Max; i++) {
                    if (shurikens [i] == null) {
                        shurikens [i] = Clone.transform;

                        textControl [i] = textObject.GetComponent<TextMesh> ();     // get the TextMesh
                        textControl [i].text = "O HOLD O";    // set initial so compiler doesnt complain
                        textPositions [i] = textObject.GetComponent<Transform> ();  // get its position

                        teleportBlast [i] = Clone.GetComponent<ParticleSystem> ();  // get its particle system

                        shurikenScripts [i] = Clone.GetComponent<ShurikenController> ();  // get its script
                        shurikenScripts [i].SetPlaced (false);

                        // Assign it the appropriate tag
                        if (i == 0)
                            Clone.gameObject.tag = "Shuriken0";
                        else if (i == 1)
                            Clone.gameObject.tag = "Shuriken1";
                        else if (i == 2)
                            Clone.gameObject.tag = "Shuriken2";
                        else if (i == 3)
                            Clone.gameObject.tag = "Shuriken3";

                        break; // found empty slot
                    }
                }
                if (facingDirection == Vector2.right) {  			// Throw to the right
                    Clone.AddForce (speed * new Vector3 (1.0f, 0.0f, 0.0f));
                    Clone.AddTorque (new Vector3 (0, 0, -turnSpeed));
                } else {    										// Throw to the left
                    Clone.AddForce (speed * new Vector3 (-1.0f, 0.0f, 0.0f));
                    Clone.AddTorque (new Vector3 (0, 0, turnSpeed));
                }
                amountUsed++;
            }
            // Place Shuriken at feet
            else if (Input.GetKeyDown (KeyCode.J)) {
                Clone = Instantiate (ShurikenPrefab, new Vector3 (spawnPlace.transform.position.x, spawnPlace.transform.position.y, -3.0f),
                                     	  Quaternion.identity) as Rigidbody;
                textObject = Instantiate (TextControlPrefab,
                                          new Vector3 (Clone.transform.position.x - 0.414f, Clone.transform.position.y + 0.352f, -3.0f),
                                          Quaternion.identity) as GameObject;

                // get first open slot
                for (int i = 0; i < Max; i++) {
                    if (shurikens [i] == null) {
                        shurikens [i] = Clone.transform;

                        textControl [i] = textObject.GetComponent<TextMesh> ();     // get the TextMesh
                        textControl [i].text = "O HOLD O";    // set initial so compiler doesnt complain
                        textPositions [i] = textObject.GetComponent<Transform> ();  // get its position

                        teleportBlast [i] = Clone.GetComponent<ParticleSystem> ();  // get its particle system

                        shurikenScripts [i] = Clone.GetComponent<ShurikenController> ();  // get its script
                        shurikenScripts [i].SetPlaced (true);   // this shuriken does not move

                        // Assign it the appropriate tag
                        if (i == 0)
                            Clone.gameObject.tag = "Shuriken0";
                        else if (i == 1)
                            Clone.gameObject.tag = "Shuriken1";
                        else if (i == 2)
                            Clone.gameObject.tag = "Shuriken2";
                        else if (i == 3)
                            Clone.gameObject.tag = "Shuriken3";

                        break; // found empty slot
                    }
                }
                amountUsed++;
            }
        }

        // update Text positions so they allign with shurikens
        for (int i = 0; i < Max; i++)
            if (shurikens [i] != null) {
                textPositions [i].position = new Vector3 (shurikens [i].position.x - 0.414f, shurikens [i].position.y + 0.352f, -3.0f);

                // is has parent then position it above it
                if (shurikens [i].parent != null)
                    textPositions [i].position += new Vector3 (0.0f, 1.0f, 0.0f);

                // if Enemy on Shuriken Position it below
                if (shurikenScripts [i].GetEnemyOnPlaced () != null)
                    textPositions [i].position -= new Vector3 (0.0f, 0.75f, 0.0f);
            }

        // When user holds down the O key alter text
        if (Input.GetKey (KeyCode.O) && !Input.GetKey (KeyCode.K)) {
            Time.timeScale = 0.2f;  // SLOW MOTION so player has time to choose

            // set controls Text
            for (int i = 0; i < Max; i++) {
                if (shurikens [i] != null)
                if (i == 0)
                    textControl [0].text = "A PRESS A";
                else if (i == 1)
                    textControl [1].text = "S PRESS S";
                else if (i == 2)
                    textControl [2].text = "D PRESS D";
                else if (i == 3)
                    textControl [3].text = "W PRESS W";
            }

            // Teleport the player to shuriken and play the effect
            if (Input.GetKeyDown (KeyCode.A) && shurikens [0] != null) {   		  // 1st shuriken
                Player.transform.position = shurikens [0].position;
                teleportBlast [0].Play (false);
            } else if (Input.GetKeyDown (KeyCode.S) && shurikens [1] != null) {    // 2nd shuriken
                Player.transform.position = shurikens [1].position;
                teleportBlast [1].Play (false);
            } else if (Input.GetKeyDown (KeyCode.D) && shurikens [2] != null) {    // 3rd shuriken
                Player.transform.position = shurikens [2].position;
                teleportBlast [2].Play (false);
            } else if (Input.GetKeyDown (KeyCode.W) && shurikens [3] != null) {    // 4th shuriken
                Player.transform.position = shurikens [3].position;
                teleportBlast [3].Play (false);
            }
        }

        // alter controls Text for shurikens with enemyOnPlaced or with a parent --> so player knows it has soemthing to teleport
        if (!Input.GetKey (KeyCode.O) && !Input.GetKey (KeyCode.K))
            for (int i = 0; i < Max; i++) {
                if (shurikens [i] != null)
                if (shurikenScripts [i].GetEnemyOnPlaced () != null || shurikens [i].parent != null)
                    textControl [i].text = "O HOLD O\nK HOLD K";    // sets if shuriken has something to teleport
                else
                    textControl [i].text = "O HOLD O";    // set back
            }

        // When user holds down K key can teleport enemy from one shuriken to another
        if (Input.GetKey (KeyCode.K) && !Input.GetKey (KeyCode.O)) {
            Time.timeScale = 0.2f;  // SLOW MOTION so player has time to choose

            // set text on those with something to teleport
            for (int i = 0; i < Max; i++) {
                if (shurikens [i] != null && (shurikenScripts [i].GetEnemyOnPlaced () != null || shurikens [i].parent != null))
                if (i == 0)
                    textControl [0].text = "A TELEPORT A";
                else if (i == 1)
                    textControl [1].text = "S TELEPORT S";
                else if (i == 2)
                    textControl [2].text = "D TELEPORT D";
                else if (i == 3)
                    textControl [3].text = "W TELEPORT W";
            }

            // Whats getting teleported
            if (Input.GetKeyDown (KeyCode.A) && isPressed [1] == false && isPressed [2] == false && isPressed [3] == false)
                isPressed [0] = true;
            else if (Input.GetKeyDown (KeyCode.S) && isPressed [0] == false && isPressed [2] == false && isPressed [3] == false)
                isPressed [1] = true;
            else if (Input.GetKeyDown (KeyCode.D) && isPressed [0] == false && isPressed [1] == false && isPressed [3] == false)
                isPressed [2] = true;
            else if (Input.GetKeyDown (KeyCode.W) && isPressed [0] == false && isPressed [1] == false && isPressed [2] == false)
                isPressed [3] = true;

            // TELEPORTING A
            if (isPressed [0] && shurikens [0] != null && (shurikenScripts [0].GetEnemyOnPlaced () != null || shurikens [0].parent != null)) {
                // Display new text, where can teleport to
                if (shurikens [1] != null)
                    textControl [1].text = "S TARGET TARGET S";
                if (shurikens [2] != null)
                    textControl [2].text = "D TARGET TARGET D";
                if (shurikens [3] != null)
                    textControl [3].text = "W TARGET TARGET W";

                // Where its getting teleported
                if (shurikenScripts [0].GetPlaced ()) { 	// placed shurikens
                    GameObject enemy = shurikenScripts [0].GetEnemyOnPlaced ().gameObject as GameObject;
                    // Teleport whats on shuriken to new location
                    if (Input.GetKeyDown (KeyCode.S) && shurikens [1] != null) {
                        enemy.transform.position = shurikens [1].position;
                        teleportBlast [1].Play (false);
                    } else if (Input.GetKeyDown (KeyCode.D) && shurikens [2] != null) {
                        enemy.transform.position = shurikens [2].position;
                        teleportBlast [2].Play (false);
                    } else if (Input.GetKeyDown (KeyCode.W) && shurikens [3] != null) {
                        enemy.transform.position = shurikens [3].position;
                        teleportBlast [3].Play (false);
                    }
                    SetLayer (enemy);
                } else {   		// mobile parented shurikens
                    // Teleport shuriken's parent to new location
                    if (Input.GetKeyDown (KeyCode.S) && shurikens [1] != null) {
                        shurikens [0].parent.position = shurikens [1].position;
                        teleportBlast [1].Play (false);

                        // can only teleport enemy once, then the shuriken gets destroyed
                        DestroyIt (0);

                    } else if (Input.GetKeyDown (KeyCode.D) && shurikens [2] != null) {
                        shurikens [0].parent.position = shurikens [2].position;
                        teleportBlast [2].Play (false);

                        // can only teleport enemy once, then the shuriken gets destroyed
                        DestroyIt (0);
                    } else if (Input.GetKeyDown (KeyCode.W) && shurikens [3] != null) {
                        shurikens [0].parent.position = shurikens [3].position;
                        teleportBlast [3].Play (false);

                        // can only teleport enemy once, then the shuriken gets destroyed
                        DestroyIt (0);
                    }
                }
            }
        // TELEPORTING S
            else if (isPressed [1] && shurikens [1] != null && (shurikenScripts [1].GetEnemyOnPlaced () != null || shurikens [1].parent != null)) {
                // Display new text, where can teleport to
                if (shurikens [0] != null)
                    textControl [0].text = "A TARGET TARGET A";
                if (shurikens [2] != null)
                    textControl [2].text = "D TARGET TARGET D";
                if (shurikens [3] != null)
                    textControl [3].text = "W TARGET TARGET W";

                // Where its getting teleported
                if (shurikenScripts [1].GetPlaced ()) {   		// placed shurikens
                    GameObject enemy = shurikenScripts [1].GetEnemyOnPlaced ().gameObject as GameObject;
                    // Teleport whats on shuriken to new location
                    if (Input.GetKeyDown (KeyCode.A) && shurikens [0] != null) {
                        enemy.transform.position = shurikens [0].position;
                        teleportBlast [0].Play (false);
                    } else if (Input.GetKeyDown (KeyCode.D) && shurikens [2] != null) {
                        enemy.transform.position = shurikens [2].position;
                        teleportBlast [2].Play (false);
                    } else if (Input.GetKeyDown (KeyCode.W) && shurikens [3] != null) {
                        enemy.transform.position = shurikens [3].position;
                        teleportBlast [3].Play (false);
                    }
                    SetLayer (enemy);
                } else if (shurikens [1].parent != null) {  		// mobile parented shurikens
                    // Teleport shuriken's parent to new location
                    if (Input.GetKeyDown (KeyCode.A) && shurikens [0] != null) {
                        shurikens [1].parent.position = shurikens [0].position;
                        teleportBlast [0].Play (false);

                        // can only teleport enemy once, then the shuriken gets destroyed
                        DestroyIt (1);
                    } else if (Input.GetKeyDown (KeyCode.D) && shurikens [2] != null) {
                        shurikens [1].parent.position = shurikens [2].position;
                        teleportBlast [2].Play (false);

                        // can only teleport enemy once, then the shuriken gets destroyed
                        DestroyIt (1);
                    } else if (Input.GetKeyDown (KeyCode.W) && shurikens [3] != null) {
                        shurikens [1].parent.position = shurikens [3].position;
                        teleportBlast [3].Play (false);

                        // can only teleport enemy once, then the shuriken gets destroyed
                        DestroyIt (1);
                    }
                }
            }
        // TELEPORTING D
            else if (isPressed [2] && shurikens [2] != null && (shurikenScripts [2].GetEnemyOnPlaced () != null || shurikens [2].parent != null)) {
                // Display new text, where can teleport to
                if (shurikens [0] != null)
                    textControl [0].text = "A TARGET TARGET A";
                if (shurikens [1] != null)
                    textControl [1].text = "S TARGET TARGET S";
                if (shurikens [3] != null)
                    textControl [3].text = "W TARGET TARGET W";

                // Where its getting teleported
                if (shurikenScripts [2].GetPlaced ()) {   		// placed shurikens
                    GameObject enemy = shurikenScripts [2].GetEnemyOnPlaced ().gameObject as GameObject;
                    // Teleport whats on shuriken to new location
                    if (Input.GetKeyDown (KeyCode.A) && shurikens [0] != null) {
                        enemy.transform.position = shurikens [0].position;
                        teleportBlast [0].Play (false);
                    } else if (Input.GetKeyDown (KeyCode.S) && shurikens [1] != null) {
                        enemy.transform.position = shurikens [1].position;
                        teleportBlast [1].Play (false);
                    } else if (Input.GetKeyDown (KeyCode.W) && shurikens [3] != null) {
                        enemy.transform.position = shurikens [3].position;
                        teleportBlast [3].Play (false);
                    }
                    SetLayer (enemy);
                } else if (shurikens [2].parent != null) {  		// mobile parented shurikens
                    // Teleport shuriken's parent to new location
                    if (Input.GetKeyDown (KeyCode.A) && shurikens [0] != null) {
                        shurikens [2].parent.position = shurikens [0].position;
                        teleportBlast [0].Play (false);

                        // can only teleport enemy once, then the shuriken gets destroyed
                        DestroyIt (2);
                    } else if (Input.GetKeyDown (KeyCode.S) && shurikens [1] != null) {
                        shurikens [2].parent.position = shurikens [1].position;
                        teleportBlast [1].Play (false);

                        // can only teleport enemy once, then the shuriken gets destroyed
                        DestroyIt (2);
                    } else if (Input.GetKeyDown (KeyCode.W) && shurikens [3] != null) {
                        shurikens [2].parent.position = shurikens [3].position;
                        teleportBlast [3].Play (false);

                        // can only teleport enemy once, then the shuriken gets destroyed
                        DestroyIt (2);
                    }
                }
            }
        // TELEPORTING W
            else if (isPressed [3] && shurikens [3] != null && (shurikenScripts [3].GetEnemyOnPlaced () != null || shurikens [3].parent != null)) {
                // Display new text, where can teleport to
                if (shurikens [0] != null)
                    textControl [0].text = "A TARGET A";
                if (shurikens [1] != null)
                    textControl [1].text = "S TARGET S";
                if (shurikens [2] != null)
                    textControl [2].text = "D TARGET D";

                // Where its getting teleported
                if (shurikenScripts [3].GetPlaced ()) {   		// placed shurikens
                    GameObject enemy = shurikenScripts [3].GetEnemyOnPlaced ().gameObject as GameObject;
                    // Teleport whats on shuriken to new location
                    if (Input.GetKeyDown (KeyCode.A) && shurikens [0] != null) {
                        enemy.transform.position = shurikens [0].position;
                        teleportBlast [0].Play (false);
                    } else if (Input.GetKeyDown (KeyCode.S) && shurikens [1] != null) {
                        enemy.transform.position = shurikens [1].position;
                        teleportBlast [1].Play (false);
                    } else if (Input.GetKeyDown (KeyCode.D) && shurikens [2] != null) {
                        enemy.transform.position = shurikens [2].position;
                        teleportBlast [2].Play (false);
                    }
                    SetLayer (enemy);
                } else if (shurikens [3].parent != null) {  		// mobile parented shurikens
                    // Teleport shuriken's parent to new location
                    if (Input.GetKeyDown (KeyCode.A) && shurikens [0] != null) {
                        shurikens [3].parent.position = shurikens [0].position;
                        teleportBlast [0].Play (false);

                        // can only teleport enemy once, then the shuriken gets destroyed
                        DestroyIt (3);
                    } else if (Input.GetKeyDown (KeyCode.S) && shurikens [1] != null) {
                        shurikens [3].parent.position = shurikens [1].position;
                        teleportBlast [1].Play (false);

                        // can only teleport enemy once, then the shuriken gets destroyed
                        DestroyIt (3);
                    } else if (Input.GetKeyDown (KeyCode.D) && shurikens [2] != null) {
                        shurikens [3].parent.position = shurikens [2].position;
                        teleportBlast [2].Play (false);

                        // can only teleport enemy once, then the shuriken gets destroyed
                        DestroyIt (3);
                    }
                }
            }
        }

        if (Input.GetKeyUp (KeyCode.O) || Input.GetKeyUp (KeyCode.K)) {
            Time.timeScale = 1.0f;    // Undo slow motion

            // set them back once user releases the O key or the K key
            for (int i = 0; i < Max; i++) {
                if (shurikens [i] != null)
                if (shurikenScripts [i].GetEnemyOnPlaced () != null || shurikens [i].parent != null)
                    textControl [i].text = "O HOLD O\nK HOLD K";    // sets if shuriken has something to teleport
                else
                    textControl [i].text = "O HOLD O";    // set back
            }

            // set bool elements to false
            for (int i = 0; i < Max; i++)
                isPressed [i] = false;
        }
    }
예제 #24
0
    private void BuildSegments(float ropeLength)
    {
        Vector3 segmentScale = new Vector3(0.025f, 0.025f, segmentLength);
        rope.hingeJoint.anchor = new Vector3(0f, 0f, -segmentLength/2f);

        float segmentsCount = Mathf.Floor (ropeLength/segmentLength);

        float totalSegments = Mathf.Ceil (totalRopeLength / segmentLength);
        float xDistance = (ropePosition.x - ropeTarget.x) / totalSegments;
        float yDistance = (ropePosition.y - ropeTarget.y) / totalSegments;

        for (float i=0f; i<segmentsCount; ++i) {
          Vector3 segmentPosition = new Vector3(
        ropePosition.x - (xDistance * (segmentCount + 0.5f)),
        ropePosition.y - (yDistance * (segmentCount + 0.5f))
          );

          Vector3 relativePos = ropeTarget - ropePosition;
          Quaternion ropeRotation = Quaternion.LookRotation(relativePos);

          Transform ropeTransform = (Instantiate (rope, segmentPosition, ropeRotation) as GameObject).transform;
          ropeTransform.localScale = segmentScale;

          ropeTransform.hingeJoint.connectedBody = ropeConnection;

          instantiatedRopeLength += segmentLength;
          ropeConnection = ropeTransform.rigidbody;
          segmentCount++;

          RopePhysics ropePhysics = ropeConnection.GetComponent<RopePhysics> ();
          ropePhysics.Attach ();

          if (ropePhysics.attached) {
        FinishRope();
        break;
          }
        }
    }
예제 #25
0
    private void Update()
    {
        if (grabbed)
        {
            if (item != null)
            {
                item.useGravity = true;
                item.isKinematic = false;
                item.AddForce(tr.up*throwForce);
                item = null;
            }
            return;
        }
        direction = Input.GetAxis("Vertical")*Vector3.forward + Input.GetAxis("Horizontal")*Vector3.right;

        if (Input.GetKeyDown("space") || Input.GetButtonDown("Jump"))
        {
            if (item == null)
            {
                characters = Physics.OverlapSphere(tr.position + tr.forward, 2, characterLayer);
                throwables = Physics.OverlapSphere(tr.position + tr.forward, 2, throwableLayer);
                if (characters.Length > 1)
                {
                    foreach (var character in characters)
                    {
                        if (character.tag != "Page")
                        {
                            isCharacter = true;
                            item = character.GetComponent<Rigidbody>();
                            item.useGravity = false;
                            item.isKinematic = true;
                            item.drag = 0;
                            if (item.tag == "Queen")
                            {
                                item.GetComponent<Queen>().grounded = false;
                                StartCoroutine(item.GetComponent<Queen>().Panic());
                            }

                            if (item.tag == "Cat" || item.name == "Cat")
                            {
                                item.GetComponent<Cat>().grounded = false;
                                StartCoroutine(item.GetComponent<Cat>().Panic());
                            }
                            if (item.tag == "Guard")
                            {
                                item.GetComponent<Guard>().grounded = false;
                                StartCoroutine(item.GetComponent<Guard>().Panic());
                            }

                            break;
                        }
                    }
                }
                else if (throwables.Length > 0)
                {
                    isCharacter = false;
                    item = throwables[0].GetComponent<Rigidbody>();
                    item.useGravity = false;
                    item.isKinematic = true;
                }
            }
            else
            {
                item.useGravity = true;
                item.isKinematic = false;
                item.AddForce((tr.forward + tr.up + Vector3.ClampMagnitude(rb.velocity, 1))*throwForce);
                item = null;
            }
        }
    }
예제 #26
0
        private void addRigidBody(Rigidbody body)
        {
            Saber attachedWeapon;
            if (body == this.rb) return;
            if (body == null) return;
            if (body.GetComponent<Saber>() != null)
            {
                attachedWeapon = body.GetComponent<Saber>();
                if (attachedWeapon.owner.DominantHandAttached) return;
            }

            foreach (Rigidbody oldBody in heldObjects)
            {
                if (oldBody == body) return;
            }
            Rigidbody[] newObjects = new Rigidbody[heldObjects.Length + 1];
            System.Array.Copy(heldObjects, newObjects, heldObjects.Length);
            newObjects[heldObjects.Length] = body;
            heldObjects = newObjects;
            if (body.GetComponent<Actor>() != null)
            {
                body.GetComponent<Actor>().CanMove = false;
            }
        }
    void InputPickup()
    {
        if (Input.GetButtonDown("Use"))
        {
            if (m_bHolding == false)
            {
                RayCast();

                if (m_bHasTarget == false)
                    return;

                m_tObject = m_rTarget.transform.GetComponent<Rigidbody>();
                if(m_tObject)
                {
                    //Debug.Log("Ray hit an object");
                    if (m_tObject.GetComponent<Prop_Basic>())
                    {
                        //Debug.Log("prop is prop hit by ray");
                        if (m_tObject.GetComponent<Prop_Basic>().isHeld() == false)
                        {
                           // Debug.Log("should be pickedup");
                            m_tObject.GetComponent<Prop_Basic>().Held();
                            m_bHolding = true;
                            //m_tObject.transform.parent = m_oHoldPosition.transform;

                            m_tObject.constraints = RigidbodyConstraints.FreezeRotation;
                            m_vObjectPosition = m_tObject.transform.position;
                        }
                        else
                        {
                            //do nothing atm maybe play disabled sound since someone else is carrying this object.
                            AudioSource.PlayClipAtPoint(m_aBreak, GetComponent<Transform>().position);
                        }
                    }
                }
            }
        }
    }
예제 #28
0
    private void FixedUpdate()
    {
        if (!grounded) return;
        newForward = tr.forward;

        if (walking)
        {
            if (followQueen)
            {
                direction = (queen.position + Quaternion.LookRotation(queen.forward, Vector3.up)*behindQueen) -
                            tr.position;
                direction.y = 0;
                if (direction.sqrMagnitude > targetDistance*targetDistance)
                {
                    if (Vector3.Angle(tr.forward, direction) > 5 && direction != Vector3.zero)
                    {
                        newForward += direction.normalized;
                    }
                    rb.AddForce(direction.normalized*moveSpeed*Time.deltaTime);
                }
            }
            else if (victim != null && path != null)
            {
                if ((path.vectorPath[path.vectorPath.Count - 1] - tr.position).sqrMagnitude >
                    targetDistance*targetDistance)
                {
                    direction = path.vectorPath[currentWaypoint] - tr.position;
                    direction.y = 0;

                    if (Vector3.Angle(tr.forward, direction) > 5 && direction != Vector3.zero)
                    {
                        newForward += direction.normalized;
                    }
                    rb.AddForce(direction.normalized*moveSpeed*Time.deltaTime);

                    if ((tr.position - path.vectorPath[currentWaypoint]).sqrMagnitude <
                        nextWaypointDistance*nextWaypointDistance && currentWaypoint < path.vectorPath.Count - 1)
                    {
                        currentWaypoint++;
                    }
                }
                else
                {
                    path = null;
                    direction = Vector3.zero;
                    throwables = Physics.OverlapSphere(tr.position + tr.forward, 2, characterLayer);
                    foreach (var throwable in throwables)
                    {
                        if (throwable.GetComponent<Rigidbody>().tag == "Page")
                        {
                            item = throwable.GetComponent<Rigidbody>();
                            item.useGravity = false;
                            item.isKinematic = true;
                            item.GetComponent<Page>().grabbed = true;
                            target = null;
                            foreach (var guard in guardList)
                            {
                                guard.victim = null;
                            }
                            item.drag = 0;
                            item.constraints = RigidbodyConstraints.None;
                            var windows = Physics.OverlapSphere(tr.position, 50, windowLayer);
                            foreach (var candidate in windows)
                            {
                                if (window == null)
                                {
                                    window = candidate.transform;
                                }
                                else if ((tr.position - candidate.transform.position).sqrMagnitude <
                                         (tr.position - window.position).sqrMagnitude)
                                {
                                    window = candidate.transform;
                                }
                            }

                            SetTarget(windows[0].transform);
                        }
                    }
                }
            }
            else if (window != null && path != null)
            {
                if ((path.vectorPath[path.vectorPath.Count - 1] - tr.position).sqrMagnitude >
                    targetDistance*targetDistance)
                {
                    direction = path.vectorPath[currentWaypoint] - tr.position;
                    direction.y = 0;

                    if (Vector3.Angle(tr.forward, direction) > 5 && direction != Vector3.zero)
                    {
                        newForward += direction.normalized;
                    }
                    rb.AddForce(direction.normalized*moveSpeed*Time.deltaTime);

                    if ((tr.position - path.vectorPath[currentWaypoint]).sqrMagnitude <
                        nextWaypointDistance*nextWaypointDistance && currentWaypoint < path.vectorPath.Count - 1)
                    {
                        currentWaypoint++;
                    }
                }
                else
                {
                    path = null;
                    direction = Vector3.zero;
                    item.useGravity = true;
                    item.isKinematic = false;
                    item.AddForce((tr.forward + tr.up + Vector3.ClampMagnitude(rb.velocity, 1))*throwForce);
                    walking = false;
                    item = null;
                    window = null;
                }
            }
        }

        if (target != null)
        {
            toTarget = target.position - head.position;
            if (Vector3.Angle(head.forward, toTarget) > 3)
            {
                head.forward = Vector3.Slerp(head.forward, toTarget, 10*Time.deltaTime);
            }
            if (Vector3.Angle(tr.forward, toTarget) > 45)
            {
                newForward += toTarget.normalized;
            }
        }
        else
        {
            if (Vector3.Angle(head.forward, tr.forward) > 3)
            {
                head.forward = Vector3.Slerp(head.forward, tr.forward, 10*Time.deltaTime);
            }
        }

        newForward.y = 0;
        if (newForward != tr.forward || tr.up != Vector3.up)
        {
            tr.rotation = Quaternion.Slerp(tr.rotation, Quaternion.LookRotation(newForward, Vector3.up),
                5*Time.deltaTime);
        }

        if (item != null)
        {
            item.position = tr.position + tr.up*5 - tr.right;
            item.rotation = tr.rotation*Quaternion.FromToRotation(Vector3.up, Vector3.right);
        }
    }
예제 #29
0
    void Update()
    {
        //If the enemy health is <= 0, destroy the enemy
        if(enemyHealth <= 0.0f){
            if(enemyIsAlive){
                if(!cannotDropWeapons){
                    npcWeaponChange = gameObject.GetComponent<NonPlayerCharacterWeaponChange>();

                    dropPoint = npcWeaponChange.dropPoint.position;

                    //Test to see if the dropPoint is being blocked by an obstacle...
                    RaycastHit wallHit;
                    if(Physics.Raycast (transform.position, (dropPoint - transform.position), out wallHit, (dropPoint - transform.position).magnitude, 1 << LayerMask.NameToLayer("Environment_Collision"))){
                        dropPoint = transform.position+(wallHit.point-transform.position)*0.8f;
                    }

                    usableWeapons = gameObject.GetComponent<UsableWeapons>();
                    if(npcWeaponChange.hasPrimaryWeap == true){
                        string equippedWeaponName = npcWeaponChange.primaryEquipped.gameObject.GetComponent<weaponIndex> ().weaponName;
                        int equippedWeaponIndex = usableWeapons.primaryUsableWeapons.IndexOf (equippedWeaponName);
                        dropWeapon = Instantiate(usableWeapons.worldPrimaryUsableWeapons [equippedWeaponIndex], dropPoint, npcWeaponChange.primarySpawnpoint.rotation) as Rigidbody;
                        dropWeapon.AddForce(GetComponent<NavMeshAgent>().velocity*npcWeaponChange.dropForce);
                        dropWeapon.AddTorque (transform.up*npcWeaponChange.dropForce*Random.Range(-0.5f, 0.5f));
                        dropWeapon.GetComponent<weaponIndex>().ammoCount = npcWeaponChange.primaryEquipped.gameObject.GetComponent<weaponIndex> ().ammoCount;
                    }
                    if(npcWeaponChange.hasSecondaryWeap == true){
                        string equippedWeaponName = npcWeaponChange.secondaryEquipped.gameObject.GetComponent<weaponIndex> ().weaponName;
                        int equippedWeaponIndex = usableWeapons.secondaryUsableWeapons.IndexOf (equippedWeaponName);
                        dropWeapon = Instantiate(usableWeapons.worldSecondaryUsableWeapons [equippedWeaponIndex], dropPoint, npcWeaponChange.secondarySpawnpoint.rotation) as Rigidbody;
                        dropWeapon.AddForce(GetComponent<NavMeshAgent>().velocity*npcWeaponChange.dropForce);
                        dropWeapon.AddTorque (transform.up*npcWeaponChange.dropForce*Random.Range(-0.5f, 0.5f));
                        dropWeapon.GetComponent<weaponIndex>().ammoCount = npcWeaponChange.secondaryEquipped.gameObject.GetComponent<weaponIndex> ().ammoCount;
                    }
                }
                if(deadBodyRandomRotation){
                    deadBodyRotation = Quaternion.AngleAxis (Random.Range (0f, 360f),Vector3.up);
                }
                else{
                    deadBodyRotation = transform.rotation;
                }
                deadBody = Instantiate (deadEnemy[damageTypeIndex], transform.position, deadBodyRotation ) as Rigidbody;

                deadBody.transform.Rotate (Vector3.right, 90f);
                if(damageForce!= Vector3.zero){
                    deadBody.AddForce (damageForce);
                }
                if(explosionForce!= 0.0f){
                    //deadBody.AddExplosionForce (explosionForce,explosionLocation, explosionRadius);
                    deadBody.AddForce (explosionForce*((transform.position - explosionLocation).normalized));
                }

                //Pick a random spawnOnDeath from the list
                if(spawnOnDeath.Count > 0){
                    int spawnIndex = 0;
                    float randomNumber = Random.value*100.0f;
                    int spawnOptionCount = spawnOnDeath.Count;
                    float minCheck = 0.0f;
                    float maxCheck = 0.0f;
                    if(randomNumber == 0.0f){
                        spawnIndex = 0;
                    }
                    else if(randomNumber == 1.0f){
                        spawnIndex = spawnOnDeath.Count - 1;
                    }
                    else{
                        for (int i=0; i < spawnOptionCount; i++){
                            maxCheck = maxCheck + percentSpawnOnDeath[i];
                            if (randomNumber >= minCheck && randomNumber < maxCheck){
                                spawnIndex = i;
                            }
                            minCheck = maxCheck;
                        }
                    }
                    Instantiate(spawnOnDeath[spawnIndex], transform.position, spawnOnDeath[spawnIndex].transform.rotation);
                }
                if(targetGO != null){
                    (targetGO.GetComponent(scriptNameToEnable) as MonoBehaviour).enabled = true;
                }
            }
            enemyIsAlive = false;
            /*if(localSceneObjectsExist){
                if(!ignoreEnemyForSceneClearing && gameObject.tag == Tags.enemy && !localScenePersistentGameObjects.isCleared){
                    sceneFadeInOut.remainingEnemiesList.Remove(gameObject);
                    sceneFadeInOut.SceneStatusCheckDelay(true);
                }
            }*/
            if(sceneFadeInOut.remainingEnemiesList.Contains (gameObject)){
                sceneFadeInOut.remainingEnemiesList.Remove(gameObject);
                sceneFadeInOut.SceneStatusCheckDelay(true);
            }
            Destroy(gameObject);

        }
    }