Ejemplo n.º 1
1
	public bool IsHoldingGrapple = false;	// if true the player is pulled alongwith the hook shot
	public void CreateGrappleBeam() {
		if (!IsGrappling) {
			HandPosition = transform.position;	// default for now
			RaycastHit hit;
			Player MyPlayer = gameObject.GetComponent<Player> ();
			if (Physics.Raycast (transform.position, MyPlayer.ShootForwardVector, out hit, 100)) {
				HandPosition = hit.point;
				Quaternion NewRotation = new Quaternion ();
				//NewRotation.eulerAngles = (hit.point - gameObject.transform.position);
				NewRotation.eulerAngles =  MyPlayer.ShootForwardVector;
				NewRotation = Quaternion.identity;
				//Debug.LogError ("Angle of Grapple: " + NewRotation.eulerAngles.ToString());
				GameObject MyChain = (GameObject)Instantiate (GrappleBeamPrefab, HandPosition, NewRotation);
				//NewRotation = MyChain.transform.rotation;
				MyChain.transform.LookAt(hit.point);
				//Debug.LogError ("Angle of Grapple: " + MyChain.transform.rotation.eulerAngles.ToString());
				if (IsHoldingGrapple) {
					//MyChain.transform.rotation = NewRotation;
					transform.position = MyChain.transform.GetChild (7).transform.position;
					Vector3 CharacterBodyOffset = new Vector3(0,-1.5f,0);
					transform.position = transform.position+CharacterBodyOffset;
					gameObject.AddComponent<FixedJoint> ();
					gameObject.GetComponent<FixedJoint> ().connectedBody = MyChain.transform.GetChild (7).GetComponent<Rigidbody> ();
					gameObject.GetComponent<CharacterController> ().enabled = false;
					IsGrappling = true;
					gameObject.GetComponent<Rigidbody>().isKinematic = false;
				}
			}
		}
	}
Ejemplo n.º 2
1
 public override PhysicsCharacter AddAvatar(string avName, Vector3 position, Quaternion rotation, Vector3 size,
                                            bool isFlying, uint localID, UUID UUID)
 {
     BasicCharacterActor act = new BasicCharacterActor {Position = position, Flying = isFlying};
     _actors.Add(act);
     return act;
 }
 public override void Fire(Vector3 direction, Quaternion rotation)
 {
     currentDistance = 0;
         base.Fire(direction,rotation);
                 BulletProjectileUp();
       amIFired = true;
 }
    // Update is called once per frame
    void FixedUpdate()
    {
        // Moving platform support
        if (activePlatform != null)
        {
            var newGlobalPlatformPoint = activePlatform.TransformPoint(activeLocalPlatformPoint);
            var moveDistance = (newGlobalPlatformPoint - activeGlobalPlatformPoint);
            if (moveDistance != Vector3.zero)
            {
                //this.transform.Translate(moveDistance);
                this.characterController.Move(moveDistance);
            }

            // If you want to support moving platform rotation as well:
            var newGlobalPlatformRotation = activePlatform.rotation * activeLocalPlatformRotation;
            var rotationDiff = newGlobalPlatformRotation * Quaternion.Inverse(activeGlobalPlatformRotation);

            // Prevent rotation of the local up vector
            rotationDiff = Quaternion.FromToRotation(rotationDiff * transform.up, transform.up) * rotationDiff;

            transform.rotation = rotationDiff * transform.rotation;

            activeGlobalPlatformPoint = transform.position;
            activeLocalPlatformPoint = activePlatform.InverseTransformPoint(transform.position);

            // If you want to support moving platform rotation as well:
            activeGlobalPlatformRotation = transform.rotation;
            activeLocalPlatformRotation = Quaternion.Inverse(activePlatform.rotation) * transform.rotation;
        }
    }
Ejemplo n.º 5
0
 void Start()
 {
     // Make the rigid body not change rotation
     if (GetComponent<Rigidbody>())
         GetComponent<Rigidbody>().freezeRotation = true;
     originalRotation = transform.localRotation;
 }
Ejemplo n.º 6
0
    void FindAttributes()
    {
        getRecordedData = false;
        GhostPathRecorder temp = GameObject.FindObjectOfType<GhostPathRecorder>();
        if( temp == null ) {
            Debug.LogError( "TestLerp coulnd't find a GhostPathRecorder in he scene." );
            return;
        }
        if( temp.recordedPositions.Count < 1 || temp.recordedYRotations.Count < 1 ) {
            Debug.LogError( "The GhostPathRecorder that TestLerp found has too little sampled positions/rotations to work." );
            return;
        }

        positions = temp.recordedPositions;
        yRotations = temp.recordedYRotations;
        sampleRate = temp.sampleRate;

        thisTransform.position = positions[0];
        thisTransform.rotation = Quaternion.Euler( new Vector3( 0f, yRotations[0], 0f ) );

        currentStartPos = positions[0];
        currentEndPos = positions[1];
        currentStartRot = Quaternion.Euler( new Vector3( 0f, yRotations[0], 0f ) );
        currentEndRot = Quaternion.Euler( new Vector3( 0f, yRotations[1], 0f ) );

        isMoving = true;
        getRecordedData = false;
    }
Ejemplo n.º 7
0
 void Start()
 {
     // Make the rigid body not change rotation
     if (rigidbody)
         rigidbody.freezeRotation = true;
     originalRotation = transform.localRotation;
 }
Ejemplo n.º 8
0
 void ControlMouse()
 {
     Vector3 mousePos = Input.mousePosition;
     mousePos = cam.ScreenToWorldPoint (new Vector3 (mousePos.x, mousePos.y,cam.transform.position.y - transform.position.y));
     targetRotation = Quaternion.LookRotation (mousePos - new Vector3(transform.position.x,0,transform.position.z));
     transform.eulerAngles = Vector3.up * Mathf.MoveTowardsAngle (transform.eulerAngles.y, targetRotation.eulerAngles.y, AimingSpeed ) ;
 }
Ejemplo n.º 9
0
    private void RotateToNext()
    {
        // set the next texture slide
        tex = (tex + 1) % maxTextures;

        if(!isBehindUser)
        {
            side = (side + 1) % maxSides;
        }
        else
        {
            if(side <= 0)
                side = maxSides - 1;
            else
                side -= 1;
        }

        if(horizontalSides[side] && horizontalSides[side].renderer)
        {
            horizontalSides[side].renderer.material.mainTexture = slideTextures[tex];
        }

        // rotate the presentation
        float yawRotation = !isBehindUser ? 360f / maxSides : -360f / maxSides;
        Vector3 rotateDegrees = new Vector3(0f, yawRotation, 0f);
        targetRotation *= Quaternion.Euler(rotateDegrees);
        isSpinning = true;
    }
Ejemplo n.º 10
0
        public static void CreateFromQuaternion(ref Quaternion quaternion, out Matrix3x3 result)
        {
            float qX2 = quaternion.X + quaternion.X;
            float qY2 = quaternion.Y + quaternion.Y;
            float qZ2 = quaternion.Z + quaternion.Z;
            float XX = qX2 * quaternion.X;
            float YY = qY2 * quaternion.Y;
            float ZZ = qZ2 * quaternion.Z;
            float XY = qX2 * quaternion.Y;
            float XZ = qX2 * quaternion.Z;
            float XW = qX2 * quaternion.W;
            float YZ = qY2 * quaternion.Z;
            float YW = qY2 * quaternion.W;
            float ZW = qZ2 * quaternion.W;

            result.X = new Vector3(
                1 - YY - ZZ,
                XY + ZW,
                XZ - YW);

            result.Y = new Vector3(
                XY - ZW,
                1 - XX - ZZ,
                YZ + XW);

            result.Z = new Vector3(
                XZ + YW,
                YZ - XW,
                1 - XX - YY);
        }
Ejemplo n.º 11
0
    /// <summary>
    /// Fires a bullet
    /// </summary>
    public void Fire(int owner, Vector3 firePosition, Quaternion fireRotation)
    {
        GameObject obj = NewObjectPooler.Get().GetPooledObject();

        if (obj == null)
        {
            Debug.LogError("Could not generate bullet from pooler");
            return;
        }

        obj.transform.position = firePosition;
        obj.transform.rotation = fireRotation;
        obj.transform.Translate(SpawnOffset);
        obj.SetActive(true);
        obj.GetComponent<Bullet>().Owner = owner;

        Vector3 bulletVelocity =
            transform.right * m_bulletSpeedForward +
            Vector3.up * m_bulletSpeedUp;

        obj.GetComponent<Rigidbody>().AddForce(bulletVelocity);

        if(PlayerManager.IsCloseToPlayer(obj.transform.position, 30.0f))
        {
            SoundManager.Get().PlaySound(SoundManager.SoundID.FIRE);
        }
    }
Ejemplo n.º 12
0
    // Update is called once per frame
    void Update()
    {
        if (Target == null)return;
        //find the vector pointing from our position to the target
        _direction = (Target.position - transform.position).normalized;
        float step = RotationSpeed * Time.deltaTime;

        //create the rotation we need to be in to look at the target
        _lookRotation = Quaternion.LookRotation(_direction, Vector3.up);

        ////rotate us over time according to speed until we are in the required rotation
        //        if (Vector3.Angle (transform.rotation.eulerAngles, _lookRotation.eulerAngles) < minimumFireAngle && Target != null)
        //		{
        //			TagetAligned = true;
        //		}
        //		else
        //		{
        //			TagetAligned = false;
        //		}
        //
        //		BroadcastMessage("TagetAlignedStatus", this, SendMessageOptions.DontRequireReceiver);
        transform.rotation = Quaternion.Slerp(transform.rotation, _lookRotation, step);
        transform.localEulerAngles = new Vector3(transform.localEulerAngles.x, transform.localEulerAngles.y, 0f);
        Vector3 newDir = Vector3.RotateTowards(transform.forward, _direction, step, 0.0F);
        Debug.DrawRay(transform.position, newDir * 50, Color.red);
    }
Ejemplo n.º 13
0
    // Use this for initialization
    void Start()
    {
        //leftArm.transform.eulerAngles = new Vector3(0f, 0f, 90f);
        leftArmTargetRotation = Quaternion.Euler(0f, 0f, 90f);
        //leftArmTargetRotation = Quaternion.Euler(0f, 0f, 80f);
        leftArmState = 1;

        //rightArm.transform.eulerAngles = new Vector3(0f, 0f, -90f);
        rightArmTargetRotation = Quaternion.Euler(0f, 0f, -90f);
        //rightArmTargetRotation = Quaternion.Euler(0f, 0f, -80f);
        rightArmState = 1;

        //leftLeg.transform.eulerAngles = new Vector3(0f, 0f, 0f);
        leftLegTargetRotation = Quaternion.Euler(0f, 0f, 0f);
        leftLegState = 1;

        //rightLeg.transform.eulerAngles = new Vector3 (0f, 0f, 0f);
        rightLegTargetRotation = Quaternion.Euler(0f, 0f, 0f);
        rightLegState = 1;
        /*

        leftArmDown.SetActive(true);
        leftArmState = 1;

        rightArmDown.SetActive(true);
        rightArmState = 1;

        leftLegDown.SetActive (true);
        leftLegState = 1;

        rightLegDown.SetActive (true);
        rightLegState = 1;
        */
    }
Ejemplo n.º 14
0
 // Use this for initialization
 void Start()
 {
     initPosition = transform.position;
     initRotation = transform.rotation;
     rigidbody.useGravity = false;
     rigidbody.freezeRotation = true;
 }
Ejemplo n.º 15
0
 protected void Start()
 {
     // get the Animator
     m_animator = gameObject.GetComponent<Animator>();
     m_initialRotation = transform.localRotation;
     m_initialPosition = transform.localPosition;
 }
Ejemplo n.º 16
0
    // Update is called once per frame
    void Update()
    {
        // Rotate the pickup
        Quaternion q = new Quaternion();
        q.eulerAngles = new Vector3 (0, Time.time*60, Mathf.Sin (Time.time*2) * 10);

        transform.localRotation = q;

        // Check if the pickup is near one of the players
        GameObject player1 = GameObject.Find ("Player1");
        GameObject player2 = GameObject.Find ("Player2");

        if( player1 != null )
        {
            if( (player1.transform.position - this.transform.position).magnitude < 2 )
            {
                GUIManager.currentScore += 100;
                Destroy(this.gameObject);
            }

        }

        if( player2 != null )
        {
            if( (player2.transform.position - this.transform.position).magnitude < 2 )
            {
                GUIManager.currentScore += 100;
                Destroy(this.gameObject);
            }

        }
    }
Ejemplo n.º 17
0
 public Event(Vector3 cpos, Quaternion rot, Interactable interact, bool hasInteracted)
 {
     position = cpos;
     interactable = interact;
     rotation = rot;
     this.hasInteracted = hasInteracted;
 }
Ejemplo n.º 18
0
    public void LookRotation(Transform character, Transform camera)
    {
        /*if(i >0) Check for controllers
            yRot = Input.GetAxis ("Mouse X") * XSensitivity;
            xRot = Input.GetAxis ("Mouse Y") * YSensitivity;
            }*/
            float deadzone = 0.25f;
            Vector2 stickInput = new Vector2(Input.GetAxis("Mouse Y") *YSensitivity, Input.GetAxis("Mouse X") *XSensitivity);
            if(stickInput.magnitude < deadzone)
                stickInput = Vector2.zero;
            else
                stickInput = stickInput.normalized * ((stickInput.magnitude - deadzone) / (1 - deadzone));

                m_CharacterTargetRot *= Quaternion.Euler (0f, stickInput.y, 0f);
                m_CameraTargetRot *= Quaternion.Euler (-stickInput.x, 0f, 0f);

            if (clampVerticalRotation) {
                m_CameraTargetRot = ClampRotationAroundXAxis (m_CameraTargetRot);
            }
            if(smooth)
            {
                character.localRotation = Quaternion.Slerp (character.localRotation, m_CharacterTargetRot,
                    smoothTime * Time.deltaTime);
                camera.localRotation = Quaternion.Slerp (camera.localRotation, m_CameraTargetRot,
                    smoothTime * Time.deltaTime);
            }
            else
            {
                character.localRotation = m_CharacterTargetRot;
                camera.localRotation = m_CameraTargetRot;
            }
    }
Ejemplo n.º 19
0
 public Quaternion(Quaternion Quaternion)
 {
     X = Quaternion.X;
     Y = Quaternion.Y;
     Z = Quaternion.Z;
     W = Quaternion.W;
 }
Ejemplo n.º 20
0
    public MeshRenderer CannonMesh; // cannon 메쉬

    void Awake ()
    {
        pv = GetComponent<PhotonView>(); 
        pv.observed = this; //PhotonView 의 observed 속성을 이 스크립트로 지정
        pv.synchronization = ViewSynchronization.Unreliable;  //PhotonView 의 observed option 속성설정
        currRot = transform.localRotation;   //회전 초기값 설정
    }
Ejemplo n.º 21
0
    // Use this for initialization
    void Start()
    {
        startPosition = transform.position;
        startRotation = transform.rotation;

        CalcValues();
    }
	public override void GetTransform(PropSocket socket, DungeonModel model, Matrix4x4 propTransform, System.Random random, out Vector3 outPosition, out Quaternion outRotation, out Vector3 outScale) {
		base.GetTransform(socket, model, propTransform, random, out outPosition, out outRotation, out outScale);
		
		var angle = random.Range(0, 1) * 180;
		var rotation = Quaternion.Euler(0, angle, 0);
		outRotation = rotation;
	}
Ejemplo n.º 23
0
        public void PlaneEqualsTest()
        {
            Plane a = new Plane(1.0f, 2.0f, 3.0f, 4.0f);
            Plane b = new Plane(1.0f, 2.0f, 3.0f, 4.0f);

            // case 1: compare between same values
            object obj = b;

            bool expected = true;
            bool actual = a.Equals(obj);
            Assert.Equal(expected, actual);

            // case 2: compare between different values
            b.Normal = new Vector3(10.0f, b.Normal.Y, b.Normal.Z);

            obj = b;
            expected = false;
            actual = a.Equals(obj);
            Assert.Equal(expected, actual);

            // case 3: compare between different types.
            obj = new Quaternion();
            expected = false;
            actual = a.Equals(obj);
            Assert.Equal(expected, actual);

            // case 3: compare against null.
            obj = null;
            expected = false;
            actual = a.Equals(obj);
            Assert.Equal(expected, actual);
        }
Ejemplo n.º 24
0
 public Enemy(int anID, string aName, Vector3 aPos, Quaternion aRot)
 {
     base.setID(anID);
     base.setName(aName);
     position = aPos;
     rotation = aRot;
 }
Ejemplo n.º 25
0
	// Update is called once per frame
	void Update () {

		lastQ = Input.gyro.attitude;
		lastAcc = Input.acceleration;

		if (Transfering) {

			counter += Time.deltaTime;

						if (counter > updateRate) {
								counter = 0;

								JSONObject json = new JSONObject ();
								json.AddField ("command", "gyro");
								json.AddField ("x", lastQ.x);
								json.AddField ("y", lastQ.y);
								json.AddField ("z", lastQ.z);
								json.AddField ("w", lastQ.w);
								json.AddField ("accX", lastAcc.x);
								json.AddField ("accY", lastAcc.y);
								json.AddField ("accZ", lastAcc.z);
								communicationManager.SendJson (json);


						}

				}

	}
Ejemplo n.º 26
0
 //change position directly
 public void ChangePosition(Transform target, float speed)
 {
     this.speed = speed;
     changingView = true;
     targetPos = target.position;
     targetRot = target.rotation;
 }
Ejemplo n.º 27
0
 public Enemy()
 {
     base.setID(1);
     base.setName("unnamed");
     position = Vector3.zero;
     rotation = new Quaternion(0,0,0,0);
 }
Ejemplo n.º 28
0
 protected override void OnUpdate(float factor, bool isFinished)
 {
     if (this.to != null)
     {
         if (this.mTrans == null)
         {
             this.mTrans = base.transform;
             this.mPos = this.mTrans.position;
             this.mRot = this.mTrans.rotation;
             this.mScale = this.mTrans.localScale;
         }
         if (this.from != null)
         {
             this.mTrans.position = this.from.position * (1f - factor) + this.to.position * factor;
             this.mTrans.localScale = this.from.localScale * (1f - factor) + this.to.localScale * factor;
             this.mTrans.rotation = Quaternion.Slerp(this.from.rotation, this.to.rotation, factor);
         }
         else
         {
             this.mTrans.position = this.mPos * (1f - factor) + this.to.position * factor;
             this.mTrans.localScale = this.mScale * (1f - factor) + this.to.localScale * factor;
             this.mTrans.rotation = Quaternion.Slerp(this.mRot, this.to.rotation, factor);
         }
         if (this.parentWhenFinished && isFinished)
         {
             this.mTrans.parent = this.to;
         }
     }
 }
Ejemplo n.º 29
0
 // Update is called once per frame
 void Update()
 {
     if (target != null) {
         look = Quaternion.LookRotation (target.transform.position - transform.position);
         transform.rotation = Quaternion.Slerp (transform.rotation, look, Time.deltaTime * 8.0F);
     }
 }
Ejemplo n.º 30
0
    protected override void GetBearingToTarget(Vector3 targetPosition)
    {
        base.GetBearingToTarget(targetPosition);

        Vector3 bearingToTarget = targetPosition - transform.position;
        targetBearing = Quaternion.LookRotation(bearingToTarget);
    }
Ejemplo n.º 31
0
 private void Update()
 {
     transform.localRotation = m_OriginalRotation * Quaternion.Euler(carController.CurrentSteerAngle, 0, 0);
 }
Ejemplo n.º 32
0
 public Quaternion GetQuaternionAttr(string key, Quaternion defaultValue = default(Quaternion))
 {
     return(GetTypedAttr <Quaternion>(key, defaultValue));
 }
 public static Quaternion RotateTowardsTarget(Vector3 vTarget, Vector3 vPos)
 {
     return Quaternion.Euler(0f, GetRotationAngle(vTarget, vPos), 0f);
 }
Ejemplo n.º 34
0
	// Update is called once per frame
	void Update () {
		// read the magnetometer / compass value and generate a quaternion
		Quaternion trueHeading = Quaternion.Euler (0, Input.compass.trueHeading, 0);
		// interpolate between old and new position
		transform.localRotation = Quaternion.Slerp (transform.localRotation, trueHeading, 0.05f);	
	}
Ejemplo n.º 35
0
 public void OnPositionSelection(Vector3 position, Vector3? facingDirection)
 {
     _rallyPoint.transform.position = position;
     _rallyPoint.transform.rotation = Quaternion.LookRotation(facingDirection.Value, Vector3.up);
 }
Ejemplo n.º 36
0
 private void SmoothToTarget()
 {
     //todo: replace with framerate independent smoothing
     m_transform.position = Vector3.Lerp(m_transform.position, m_target.position, m_lerpRate);
     m_transform.rotation = Quaternion.Slerp(m_transform.rotation, m_target.rotation, m_lerpRate);
 }
Ejemplo n.º 37
0
		internal static extern void Internal_DrawTube(ref Vector3 position, ref Quaternion orientation, float radius, float length, ref Color color, float duration, bool depthTest);
Ejemplo n.º 38
0
    void LateUpdate()
    {
        Instance = this;

        if (!HasCamera)
        {
            return;
        }

        if (!HasTarget)
        {
            return;
        }

        bool rotate    = RPGControllerUtils.GetButtonSafe(MouseRotateButton, false);
        bool mouseLook = RPGControllerUtils.GetButtonSafe(MouseLookButton, false);

        bool  smoothRotation      = SmoothRotation || SmoothAutoRotation;
        float smoothRotationSpeed = SmoothRotationSpeed;

        // This defines our "real" distance to the player
        realDistance -= RPGControllerUtils.GetAxisRawSafe(ZoomAxis, 0f) * ZoomSpeed;
        realDistance  = Mathf.Clamp(realDistance, MinDistance, MaxDistance);

        // This is the distance we want to (clamped to what is viewable)
        targetDistance = realDistance;
        targetDistance = Mathf.Clamp(targetDistance, currentMinDistance, currentMaxDistance);

        // This is our current distance
        if (SmoothZoom)
        {
            currentDistance = Mathf.Lerp(currentDistance, targetDistance, Time.deltaTime * SmoothZoomSpeed);
        }
        else
        {
            currentDistance = targetDistance;
        }

        // Calculate offset vector
        Vector3 offset = new Vector3(0, 0, -currentDistance);

        // LMB is not down, but we should rotate camera behind target
        if (!rotate && RotateCameraBehindTarget)
        {
            targetYaw           = RPGControllerUtils.SignedAngle(offset.normalized, -Target.forward, Vector3.up);
            smoothRotation      = SmoothAutoRotation;
            smoothRotationSpeed = SmoothAutoRotationSpeed;
        }

        // Only LMB down and no lock
        if (rotate && !mouseLook && !LockCameraBehindTarget)
        {
            targetYaw          += (RPGControllerUtils.GetAxisRawSafe(YawAxis, 0f) * RotationMouseSpeed);
            targetPitch        -= (RPGControllerUtils.GetAxisRawSafe(PitchAxis, 0f) * RotationMouseSpeed);
            targetPitch         = Mathf.Clamp(targetPitch, MinPitch, MaxPitch);
            smoothRotation      = SmoothRotation;
            smoothRotationSpeed = SmoothRotationSpeed;
        }

        // RMB
        if (mouseLook && LockCameraBehindTarget)
        {
            targetPitch -= (RPGControllerUtils.GetAxisRawSafe(PitchAxis, 0f) * RotationMouseSpeed);
            targetPitch  = Mathf.Clamp(targetPitch, MinPitch, MaxPitch);
        }

        // Lock camera behind target, this overrides everything
        if (LockCameraBehindTarget)
        {
            targetYaw      = RPGControllerUtils.SignedAngle(offset.normalized, -Target.transform.forward, Vector3.up);
            smoothRotation = false;
        }

        // Clamp targetYaw to -180, 180
        targetYaw = Mathf.Repeat(targetYaw + 180f, 360f) - 180f;

        if (!smoothRotation)
        {
            currentYaw   = targetYaw;
            currentPitch = targetPitch;
        }
        else
        {
            // Clamp smooth currentYaw to targetYaw and clamp it to -180, 180
            currentYaw = Mathf.LerpAngle(currentYaw, targetYaw, Time.deltaTime * smoothRotationSpeed);
            currentYaw = Mathf.Repeat(currentYaw + 180f, 360f) - 180f;

            // Smooth pitch
            currentPitch = Mathf.LerpAngle(currentPitch, targetPitch, Time.deltaTime * smoothRotationSpeed);
        }

        // ray hit
        RaycastHit hit = default(RaycastHit);

        // Rotate offset vector
        offset = Quaternion.Euler(currentPitch, currentYaw, 0f) * offset;

        if (Physics.Raycast(transform.position, Vector3.down, out hit, 2048f, Obstacles) && hit.transform.GetComponent <TerrainCollider>() != null)
        {
            yClamp = hit.point.y + Camera.near;
        }
        else
        {
            yClamp = float.MinValue;
        }

        // Position camera holder correctly
        transform.position = TargetPosition + offset;

        Vector3 p = transform.position;

        transform.position = new Vector3(p.x, Mathf.Clamp(p.y, yClamp, float.MaxValue), p.z);

        //float y = Mathf.Clamp(p.y, yClamp, float.MaxValue)

        // And then have the camera look at our target
        Camera.transform.LookAt(TargetPosition);

        Vector3 targetToCam = transform.position - TargetPosition;

        if (Physics.Raycast(TargetPosition, targetToCam.normalized, out hit, MaxDistance, Obstacles))
        {
            currentMinDistance = Mathf.Min(currentMinDistance, 1f);
            currentMaxDistance = Mathf.Max(currentMinDistance + 0.05f, (hit.point - Target.position).magnitude * 0.95f);
        }
        else
        {
            currentMinDistance = MinDistance;
            currentMaxDistance = MaxDistance;
        }

        // Clear this flag
        LockCameraBehindTarget   = false;
        RotateCameraBehindTarget = false;
    }
Ejemplo n.º 39
0
		private static Transform CreateModelFrom (
			Core_Voxel.Result.VoxelNode vNode, VoxelData.MaterialData[] materials, Transform parent, Vector3 pivot,
			ref List<Mesh> meshs, ref Dictionary<Texture2D, Material[]> materialsMap,
			bool isRig, bool withAvatar, Shader[] shaders, string[] shaderKeywords, Vector2[] shaderRemaps, float modelScale
		) {

			Quaternion rot = vNode.Rotation;
			Vector3 pivotFixOffset = rot * pivot;
			Vector3 fixedModelSize = rot * vNode.Size.ToVector3();
			pivotFixOffset.Scale(fixedModelSize);
			Vector3 scaleFix = rot * (0.5f * (Vector3.one - vNode.Scale.ToVector3()));
			Vector3 fixedMvPos = vNode.Position.ToVector3();

			for (int i = 0; i < 3; i++) {
				fixedMvPos[i] += (Mathf.RoundToInt(fixedModelSize[i]) % 2) * 0.5f * (scaleFix[i] > 0.5f ? -1 : 1);
			}

			var root = new GameObject().transform;
			root.SetParent(parent);
			root.localRotation = vNode.Rotation;
			root.localScale = vNode.Scale.ToVector3();
			root.gameObject.SetActive(vNode.Active);

			var nodeName = !string.IsNullOrEmpty(vNode.Name) ? vNode.Name : ("Model " + (parent.childCount - 1).ToString());

			if (vNode.Model != null) {
				root.name = nodeName;
				// BAS: FIX rotated position
				fixedModelSize = Util.VectorAbs(fixedModelSize);
				root.localPosition = (fixedMvPos - 0.5f * fixedModelSize + pivotFixOffset) * modelScale;

				// Empty Check
				bool isEmpty = true;
				var uMesh = vNode.Model;
				if (uMesh.Count > 0) {
					for (int i = 0; i < uMesh.Count; i++) {
						if (uMesh[i].vertexCount > 0) {
							isEmpty = false;
							break;
						}
					}
				}

				if (!isEmpty) {

					// Add Assets
					Texture2D texture = vNode.Texture;
					if (!texture) {
						texture = new Texture2D(4, 4);
					}

					Material[] mats;
					if (!materialsMap.ContainsKey(texture)) {
						Dictionary<int, Material> matMap = new Dictionary<int, Material>();
						for (int i = 0; i < uMesh.Count; i++) {
							int matIndex = uMesh.GetMaterialIndexAt(i);
							Material mat;
							if (matMap.ContainsKey(matIndex)) {
								mat = matMap[matIndex];
							} else {
								mat = VoxelData.GetMaterialFrom(materials[matIndex], texture, shaders, shaderKeywords, shaderRemaps);
								matMap.Add(matIndex, mat);
							}
						}
						mats = new Material[matMap.Count];
						foreach (var indexMat in matMap) {
							var mat = indexMat.Value;
							mat.name = GetIndexedName(nodeName, indexMat.Key, matMap.Count);
							mats[indexMat.Key] = mat;
						}
						texture.name = nodeName;
						materialsMap.Add(texture, mats);
					} else {
						mats = materialsMap[texture];
					}

					// Add Mesh To
					if (uMesh.Count == 1) {
						var mesh = uMesh[0];
						int matIndex = uMesh.GetMaterialIndexAt(0);
						if (!meshs.Contains(mesh)) {
							mesh.name = nodeName;
							meshs.Add(mesh);
						}
						AddMeshTo(mesh, root, mats[matIndex], isRig);
					} else {
						for (int i = 0; i < uMesh.Count; i++) {
							var target = new GameObject("m_" + i.ToString()).transform;
							target.SetParent(root);
							target.SetAsLastSibling();
							target.localPosition = Vector3.zero;
							target.localRotation = Quaternion.identity;
							target.localScale = Vector3.one;
							var mesh = uMesh[i];
							if (!meshs.Contains(mesh)) {
								mesh.name = GetIndexedName(nodeName, i, uMesh.Count);
								meshs.Add(mesh);
							}
							int matIndex = uMesh.GetMaterialIndexAt(i);
							AddMeshTo(mesh, target, mats[matIndex], false);
						}
					}
				}


			} else if (vNode.Children != null && vNode.Children.Length > 0) {
				// Sub Objects
				root.name = nodeName;
				root.localPosition = vNode.Position.ToVector3() * modelScale;
				for (int i = 0; i < vNode.Children.Length; i++) {
					CreateModelFrom(vNode.Children[i], materials, root, pivot, ref meshs, ref materialsMap, isRig, withAvatar, shaders, shaderKeywords, shaderRemaps, modelScale);
				}
			}
			return root;
		}
Ejemplo n.º 40
0
        void Update()
        {
            // fetch the fft spectrum
            audioSource.GetSpectrumData(fft, 0, FFTWindow.BlackmanHarris);

            // get raw data for waveform
            audioSource.GetOutputData(data, 0);

            // calculate root mean square (volume)
            rms = RMS(data);

            /**
             * For each face, translate the vertices some distance depending on the frequency range assigned.
             * Not using the TranslateVertices() pb_Object extension method because as a convenience, that method
             * gathers the sharedIndices per-face on every call, which while not tremondously expensive in most
             * contexts, is far too slow for use when dealing with audio, and especially so when the mesh is
             * somewhat large.
             */
            for (int i = 0; i < outsides.Length; i++)
            {
                float normalizedIndex = (i / faces_length);

                int n = (int)(normalizedIndex * fftBounds);

                Vector3 displacement = outsides[i].nrm * (((fft[n] + fft_history[n]) * .5f) * (frequencyCurve.Evaluate(normalizedIndex) * .5f + .5f)) * extrusion;

                foreach (int t in outsides[i].indices)
                {
                    displaced_vertices[t] = original_vertices[t] + displacement;
                }
            }

            Vector3 vec = Vector3.zero;

            // Waveform ring
            for (int i = 0; i < WAVEFORM_SAMPLES; i++)
            {
                int n = i < WAVEFORM_SAMPLES - 1 ? i : 0;
                vec.x = Mathf.Cos((float)n / WAVEFORM_SAMPLES * TWOPI) * (waveformRadius + (((data[n] + data_history[n]) * .5f) * waveformHeight));
                vec.z = Mathf.Sin((float)n / WAVEFORM_SAMPLES * TWOPI) * (waveformRadius + (((data[n] + data_history[n]) * .5f) * waveformHeight));

                vec.y = 0f;

                waveform.SetPosition(i, vec);
            }

            // Ring rotation
            if (rotateWaveformRing)
            {
                Vector3 rot = waveform.transform.localRotation.eulerAngles;

                rot.x = Mathf.PerlinNoise(Time.time * waveformSpeed, 0f) * 360f;
                rot.y = Mathf.PerlinNoise(0f, Time.time * waveformSpeed) * 360f;

                waveform.transform.localRotation = Quaternion.Euler(rot);
            }

            icoPosition.y         = -verticalBounce + ((rms + rms_history) * verticalBounce);
            icoTransform.position = icoPosition;

            // Keep copy of last FFT samples so we can average with the current.  Smoothes the movement.
            System.Array.Copy(fft, fft_history, FFT_SAMPLES);
            System.Array.Copy(data, data_history, WAVEFORM_SAMPLES);
            rms_history = rms;

            icoMesh.vertices = displaced_vertices;
        }
        public void Update()
        {
            if (Input.GetKey(KeyCode.Escape))
            {
                Application.Quit();
            }

            if (localImage == null)
            {
                var filePath = "/data/data/com.sumera.argallery.unity/files/test.png";
                localImage = LoadPNG(filePath);
                var rawImage = picture.GetComponentInChildren <RawImage> ();
                rawImage.texture = localImage;
                var pictureSize = CalculateSizeOfPicture(localImage);
                picture.transform.localScale = new Vector3(picture.transform.localScale.x * pictureSize.x, picture.transform.localScale.y, picture.transform.localScale.z * pictureSize.y);
            }

            if (pictureCopy == null)
            {
                pictureCopy = Instantiate(picture);
            }

            QuitOnConnectionErrors();

            if (!isFirstPointAnchored)
            {
                wallsAddingCompleteButton.gameObject.transform.parent.gameObject.SetActive(false);
                anchorPicture.gameObject.transform.parent.gameObject.SetActive(false);
                releasePicture.gameObject.transform.parent.gameObject.SetActive(false);
                wall.gameObject.SetActive(false);
            }

            if (isFirstPointAnchored && !isWallPlacingFinished)
            {
                wallsAddingCompleteButton.gameObject.transform.parent.gameObject.SetActive(true);
                anchorPicture.gameObject.transform.parent.gameObject.SetActive(false);
                releasePicture.gameObject.transform.parent.gameObject.SetActive(false);
                wall.gameObject.SetActive(true);
            }

            if (isFirstPointAnchored && isWallPlacingFinished)
            {
                wallsAddingCompleteButton.gameObject.transform.parent.gameObject.SetActive(false);

                if (isPictureAnchored)
                {
                    anchorPicture.gameObject.transform.parent.gameObject.SetActive(false);
                    releasePicture.gameObject.transform.parent.gameObject.SetActive(true);
                }
                else
                {
                    anchorPicture.gameObject.transform.parent.gameObject.SetActive(true);
                    releasePicture.gameObject.transform.parent.gameObject.SetActive(false);
                }
            }

            if (Session.Status != SessionStatus.Tracking)
            {
                const int lostTrackingSleepTimeout = 15;
                Screen.sleepTimeout = lostTrackingSleepTimeout;
                if (!isQuitting && Session.Status.IsValid())
                {
                    initialTrackingDescription.enabled = true;
                    SetWallsActive(false);
                    SetPictureActive(false);
                    wallsAddingCompleteButton.gameObject.transform.parent.gameObject.SetActive(false);
                    anchorPicture.gameObject.transform.parent.gameObject.SetActive(false);
                    releasePicture.gameObject.transform.parent.gameObject.SetActive(false);
                }

                return;
            }

            Screen.sleepTimeout = SleepTimeout.NeverSleep;

            Session.GetTrackables <TrackedPlane>(newPlanes, TrackableQueryFilter.All);
            for (int i = 0; i < newPlanes.Count; i++)
            {
                if (!wasTracked)
                {
                    wasTracked = true;
                    GameObject planeObject = Instantiate(trackedPlanePrefab, Vector3.zero, Quaternion.identity, transform);
                    planeObject.GetComponent <TrackedPlaneVisualizer> ().Initialize(newPlanes [i]);
                    trackedPlane = planeObject;
                    Session.CreateAnchor(newPlanes [i].CenterPose, newPlanes [i]);
                }
            }

            if (wasTracked && !isWallPlacingFinished)
            {
                screenOverlay.gameObject.SetActive(true);
            }
            else
            {
                screenOverlay.gameObject.SetActive(false);
            }

            Session.GetTrackables <TrackedPlane>(allPlanes);
            bool showSearchingUI = true;

            for (int i = 0; i < allPlanes.Count; i++)
            {
                if (allPlanes[i].TrackingState == TrackingState.Tracking)
                {
                    showSearchingUI = false;
                    break;
                }
            }

            SetWallsActive(!showSearchingUI && areWallsVisible);
            SetPictureActive(!showSearchingUI);
            initialTrackingDescription.enabled = showSearchingUI;

            if (isFirstPointAnchored && !isWallPlacingFinished)
            {
                var lastPointsPosition    = trackingPoints[trackingPoints.Count - 1].transform.position;
                var trackingPointPosition = new Vector3(trackingPoint.transform.position.x, lastPointsPosition.y, trackingPoint.transform.position.z);
                var newPosition           = (lastPointsPosition + trackingPointPosition) / 2;
                wall.transform.position = newPosition;
                wall.transform.LookAt(new Vector3(trackingPoint.transform.position.x, lastPointsPosition.y, trackingPoint.transform.position.z));
                var wallWidth = Vector3.Distance(lastPointsPosition, trackingPointPosition);
                wall.transform.localScale = new Vector3(0.001f, 5f, wallWidth);
                wall.transform.position  += new Vector3(0, 2.5f, 0);
                wallColliders.ForEach((collider) => collider.enabled = false);
            }

            if (isWallPlacingFinished && !isPictureAnchored)
            {
                wallColliders.ForEach((collider) => collider.enabled = true);

                trackingPoint.gameObject.SetActive(false);

                var        pictureRaycast = FirstPersonCamera.ViewportPointToRay(new Vector3(0.5f, 0.5f, 0f));
                RaycastHit pictureHit;
                if (Physics.Raycast(pictureRaycast, out pictureHit))
                {
                    if (pictureHit.transform.tag == "wall")
                    {
                        var hitRotation     = pictureHit.transform.rotation.eulerAngles;
                        var pictureRotation = picture.transform.rotation;

                        var firstPicturePosition = new Vector3(pictureHit.point.x, pictureHit.point.y, pictureHit.point.z);
                        picture.transform.rotation = Quaternion.Euler(90, hitRotation.y - 90, pictureRotation.z);
                        picture.transform.position = firstPicturePosition;
                        picture.transform.Translate(picture.transform.forward * 0.01f);

                        var secondPicturePosition = new Vector3(pictureHit.point.x, pictureHit.point.y, pictureHit.point.z);
                        pictureCopy.transform.rotation = Quaternion.Euler(90, hitRotation.y + 90, pictureRotation.z);
                        pictureCopy.transform.position = secondPicturePosition;
                        pictureCopy.transform.Translate(pictureCopy.transform.forward * 0.01f);

                        var cameraPosition        = FirstPersonCamera.transform.position;
                        var firstPictureDistance  = Vector3.Distance(cameraPosition, picture.transform.position);
                        var secondPictureDistance = Vector3.Distance(cameraPosition, pictureCopy.transform.position);

                        if (firstPictureDistance <= secondPictureDistance)
                        {
                            picture.GetComponent <Renderer>().enabled     = true;
                            pictureCopy.GetComponent <Renderer>().enabled = false;
                        }
                        else
                        {
                            picture.GetComponent <Renderer>().enabled     = false;
                            pictureCopy.GetComponent <Renderer>().enabled = true;
                        }
                    }
                }
            }

            Ray        raycast = FirstPersonCamera.ViewportPointToRay(new Vector3(0.5f, 0.5f, 0f));
            RaycastHit raycastHit;

            if (Physics.Raycast(raycast, out raycastHit))
            {
                if (raycastHit.transform.tag == "floor")
                {
                    trackingPoint.transform.position = raycastHit.point;
                }
            }
        }
Ejemplo n.º 42
0
        public void ReadProperties(RobloxBinaryFile file)
        {
            INST type = file.Types[TypeIndex];

            FileProperty[] props = new FileProperty[type.NumInstances];

            int[] ids       = type.InstanceIds;
            int   instCount = type.NumInstances;

            for (int i = 0; i < instCount; i++)
            {
                int          id       = ids[i];
                FileInstance instance = file.Instances[id];

                FileProperty prop = new FileProperty();
                prop.Instance = instance;
                prop.Name     = Name;
                prop.Type     = Type;

                props[i] = prop;
                instance.AddProperty(ref prop);
            }

            // Setup some short-hand functions for actions frequently used during the read procedure.
            var readInts   = new Func <int[]>(() => Reader.ReadInts(instCount));
            var readFloats = new Func <float[]>(() => Reader.ReadFloats(instCount));

            var loadProperties = new Action <Func <int, object> >(read =>
            {
                for (int i = 0; i < instCount; i++)
                {
                    object result  = read(i);
                    props[i].Value = result;
                }
            });

            // Read the property data based on the property type.
            // NOTE: This only reads the property types needed for Rbx2Source.
            //       You can visit the following link for a full implementation:
            //       https://github.com/CloneTrooper1019/Roblox-File-Format/blob/master/BinaryFormat/ChunkTypes/PROP.cs

            switch (Type)
            {
            case PropertyType.String:
                loadProperties(i => Reader.ReadString());
                break;

            case PropertyType.Bool:
                loadProperties(i => Reader.ReadBoolean());
                break;

            case PropertyType.Int:
                int[] ints = readInts();
                loadProperties(i => ints[i]);
                break;

            case PropertyType.Float:
                float[] floats = readFloats();
                loadProperties(i => floats[i]);
                break;

            case PropertyType.Double:
                loadProperties(i => Reader.ReadDouble());
                break;

            case PropertyType.Vector3:
                float[] Vector3_X = readFloats(),
                Vector3_Y = readFloats(),
                Vector3_Z = readFloats();

                loadProperties(i =>
                {
                    float x = Vector3_X[i],
                    y       = Vector3_Y[i],
                    z       = Vector3_Z[i];

                    return(new Vector3(x, y, z));
                });

                break;

            case PropertyType.BrickColor:
                int[] brickColorIds = readInts();

                loadProperties(i =>
                {
                    int brickColorId = brickColorIds[i];
                    return(BrickColor.FromNumber(brickColorId));
                });

                break;

            case PropertyType.CFrame:
            case PropertyType.Quaternion:
                // Temporarily load the rotation matrices into their properties.
                // We'll update them to CFrames once we iterate over the position data.

                loadProperties(i =>
                {
                    int normXY = Reader.ReadByte();

                    if (normXY > 0)
                    {
                        // Make sure this value is in a safe range.
                        normXY = (normXY - 1) % 36;

                        NormalId normX = (NormalId)(normXY / 6);
                        Vector3 R0     = Vector3.FromNormalId(normX);

                        NormalId normY = (NormalId)(normXY % 6);
                        Vector3 R1     = Vector3.FromNormalId(normY);

                        // Compute R2 using the cross product of R0 and R1.
                        Vector3 R2 = R0.Cross(R1);

                        // Generate the rotation matrix and return it.
                        return(new float[9]
                        {
                            R0.X, R0.Y, R0.Z,
                            R1.X, R1.Y, R1.Z,
                            R2.X, R2.Y, R2.Z,
                        });
                    }
                    else if (Type == PropertyType.Quaternion)
                    {
                        float qx = Reader.ReadFloat(), qy = Reader.ReadFloat(),
                        qz       = Reader.ReadFloat(), qw = Reader.ReadFloat();

                        Quaternion quaternion = new Quaternion(qx, qy, qz, qw);
                        var rotation          = quaternion.ToCFrame();

                        return(rotation.GetComponents());
                    }
                    else
                    {
                        float[] matrix = new float[9];

                        for (int m = 0; m < 9; m++)
                        {
                            float value = Reader.ReadFloat();
                            matrix[m]   = value;
                        }

                        return(matrix);
                    }
                });

                float[] CFrame_X = readFloats(),
                CFrame_Y = readFloats(),
                CFrame_Z = readFloats();

                loadProperties(i =>
                {
                    float[] matrix = props[i].Value as float[];

                    float x = CFrame_X[i],
                    y       = CFrame_Y[i],
                    z       = CFrame_Z[i];

                    float[] position = new float[3] {
                        x, y, z
                    };
                    float[] components = position
                                         .Concat(matrix)
                                         .ToArray();

                    return(new CFrame(components));
                });

                break;

            case PropertyType.Enum:
                uint[] enums = Reader.ReadInterleaved(instCount, BitConverter.ToUInt32);
                loadProperties(i => enums[i]);

                break;

            case PropertyType.Ref:
                int[] instIds = Reader.ReadInstanceIds(instCount);

                loadProperties(i =>
                {
                    int instId = instIds[i];
                    return(instId >= 0 ? file.Instances[instId] : null);
                });

                break;

            case PropertyType.Color3uint8:
                byte[] Color3uint8_R = Reader.ReadBytes(instCount),
                Color3uint8_G = Reader.ReadBytes(instCount),
                Color3uint8_B = Reader.ReadBytes(instCount);

                loadProperties(i =>
                {
                    byte r = Color3uint8_R[i],
                    g      = Color3uint8_G[i],
                    b      = Color3uint8_B[i];

                    return(Color.FromArgb(r, g, b));
                });

                break;

            case PropertyType.Int64:
                long[] int64s = Reader.ReadInterleaved(instCount, (buffer, start) =>
                {
                    long result = BitConverter.ToInt64(buffer, start);
                    return((long)((ulong)result >> 1) ^ (-(result & 1)));
                });

                loadProperties(i => int64s[i]);
                break;
            }

            Reader.Dispose();
        }
	// ------------------------------------------------------------
	// Name	:	OnUpdate
	// Desc	:	Called by the state machine each frame to give this
	//			state a time-slice to update itself. It processes 
	//			threats and handles transitions as well as keeping
	//			the zombie aligned with its proper direction in the
	//			case where root rotation isn't being used.
	// ------------------------------------------------------------
	public override AIStateType OnUpdate ()
	{
		// Do we have a visual threat that is the player
		if (_zombieStateMachine.VisualThreat.type==AITargetType.Visual_Player)
		{
			_zombieStateMachine.SetTarget ( _zombieStateMachine.VisualThreat );
			return AIStateType.Pursuit;
		}

		if (_zombieStateMachine.VisualThreat.type==AITargetType.Visual_Light)
		{
			_zombieStateMachine.SetTarget ( _zombieStateMachine.VisualThreat );
			return AIStateType.Alerted;
		}

		// Sound is the third highest priority
		if (_zombieStateMachine.AudioThreat.type==AITargetType.Audio)
		{
			_zombieStateMachine.SetTarget (_zombieStateMachine.AudioThreat );
			return AIStateType.Alerted;
		}

		// We have seen a dead body so lets pursue that if we are hungry enough
		if (_zombieStateMachine.VisualThreat.type==AITargetType.Visual_Food)
		{
			// If the distance to hunger ratio means we are hungry enough to stray off the path that far
			if ( (1.0f- _zombieStateMachine.satisfaction) > (_zombieStateMachine.VisualThreat.distance/_zombieStateMachine.sensorRadius)  )
			{
				_stateMachine.SetTarget ( _stateMachine.VisualThreat );
				return AIStateType.Pursuit;
			}
		}

		// If path is still be computed then wait
		if (_zombieStateMachine.navAgent.pathPending) 
		{
			_zombieStateMachine.speed = 0;
			return AIStateType.Patrol;
		}
		else
			_zombieStateMachine.speed = _speed;

		// Calculate angle we need to turn through to be facing our target
		float angle = Vector3.Angle (_zombieStateMachine.transform.forward, (_zombieStateMachine.navAgent.steeringTarget - _zombieStateMachine.transform.position));

		// If its too big then drop out of Patrol and into Altered
		if (angle > _turnOnSpotThreshold) 
		{
			return AIStateType.Alerted;
		}

		// If root rotation is not being used then we are responsible for keeping zombie rotated
		// and facing in the right direction. 
		if (!_zombieStateMachine.useRootRotation) 
		{
			// Generate a new Quaternion representing the rotation we should have
			Quaternion newRot = Quaternion.LookRotation (_zombieStateMachine.navAgent.desiredVelocity);

			// Smoothly rotate to that new rotation over time
			_zombieStateMachine.transform.rotation = Quaternion.Slerp( _zombieStateMachine.transform.rotation, newRot, Time.deltaTime * _slerpSpeed);
		}

		// If for any reason the nav agent has lost its path then call the NextWaypoint function
		// so a new waypoint is selected and a new path assigned to the nav agent.
		if (_zombieStateMachine.navAgent.isPathStale || 
			!_zombieStateMachine.navAgent.hasPath   ||
			_zombieStateMachine.navAgent.pathStatus!=NavMeshPathStatus.PathComplete) 
		{
			_zombieStateMachine.navAgent.SetDestination(_zombieStateMachine.GetWaypointPosition ( true ));
		}


		// Stay in Patrol State
		return AIStateType.Patrol;
	}
Ejemplo n.º 44
0
        public static void DoGUI(string title, string[] groupNames, ref bool show, ref Vector2 scrollPos, GetValueFunc getValue, SetValueFunc setValue, bool allowBothCombinations = true)
        {
            int num = 0;
            for (int i = 0; i < groupNames.Length; i++)
            {
                if (!string.IsNullOrEmpty(groupNames[i]))
                {
                    num++;
                }
            }
            if (string.IsNullOrEmpty(title))
            {
                show = true;
            }
            else
            {
                GUILayout.BeginHorizontal(new GUILayoutOption[0]);
                GUILayout.Space(0f);
                show = EditorGUILayout.Foldout(show, title);
                GUILayout.EndHorizontal();
            }
            if (show)
            {
                scrollPos = GUILayout.BeginScrollView(scrollPos, new GUILayoutOption[]
				{
					GUILayout.MinHeight(250f),
					GUILayout.MaxHeight((float)(100 + (num + 1) * 16))
				});
                Rect rect = GUILayoutUtility.GetRect((float)(16 * num + 100), 100f);
                Rect topmostRect = GUIClip_topmostRect();//GUIClip.topmostRect;
                Vector2 vector = GUIClip_Unclip(new Vector2(rect.x, rect.y));//GUIClip.Unclip(new Vector2(rect.x, rect.y));
                int num2 = 0;
                for (int j = 0; j < groupNames.Length; j++)
                {
                    if (groupNames[j] != string.Empty)
                    {
                        float num3 = (float)(130 + (num - num2) * 16) - (topmostRect.width + scrollPos.x);
                        if (num3 < 0f)
                        {
                            num3 = 0f;
                        }
                        Vector3 pos = new Vector3((float)(130 + 16 * (num - num2)) + vector.y + vector.x + scrollPos.y - num3, vector.y + scrollPos.y, 0f);
                        GUI.matrix = Matrix4x4.TRS(pos, Quaternion.identity, Vector3.one) * Matrix4x4.TRS(Vector3.zero, Quaternion.Euler(0f, 0f, 90f), Vector3.one);
                        if (SystemInfo.graphicsDeviceVersion.StartsWith("Direct3D 9.0"))
                        {
                            GUI.matrix *= Matrix4x4.TRS(new Vector3(-0.5f, -0.5f, 0f), Quaternion.identity, Vector3.one);
                        }
                        GUI.Label(new Rect(2f - vector.x - scrollPos.y, scrollPos.y - num3, 100f, 16f), groupNames[j], "RightLabel");
                        num2++;
                    }
                }
                GUI.matrix = Matrix4x4.identity;
                num2 = 0;
                for (int k = 0; k < groupNames.Length; k++)
                {
                    if (groupNames[k] != string.Empty)
                    {
                        int num4 = 0;
                        Rect rect2 = GUILayoutUtility.GetRect((float)(30 + 16 * num + 100), 16f);
                        GUI.Label(new Rect(rect2.x + 2f, rect2.y, 100f, 16f), groupNames[k], "RightLabel");
                        for (int l = groupNames.Length - 1; l >= 0; l--)
                        {
                            if (groupNames[l] != string.Empty)
                            {
                                //if (num4 < num - num2)
                                {
                                    GUIContent content = new GUIContent(string.Empty, groupNames[k] + "/" + groupNames[l]);
                                    bool flag = getValue(k, l);
                                    bool flag2 = GUI.Toggle(new Rect(130f + rect2.x + (float)(num4 * 16), rect2.y, 16f, 16f), flag, content);
                                    if (flag2 != flag)
                                    {
                                        setValue(k, l, flag2);
                                    }
                                }
                                num4++;
                            }
                        }
                        num2++;
                    }
                }
                GUILayout.EndScrollView();
            }
        }
 protected override void FixedUpdate()
 {
     base.FixedUpdate();
     transform.rotation = Quaternion.Euler(new Vector3(0, 0, turnSpeed) + transform.rotation.eulerAngles);
 }
Ejemplo n.º 46
0
 private void Start()
 {
     particle = transform.Find("Trail").GetComponent<ParticleSystem>();
     cam = Camera.main;
     transform.rotation = Quaternion.Euler(new Vector(0, 0, 180));
 }
    private void Init()
    { 
        initPosition = new Vector3(this.transform.position.x, this.transform.position.y, this.transform.position.z);
        initRotation = new Quaternion(this.transform.rotation.x, this.transform.rotation.y, this.transform.rotation.z, this.transform.rotation.w);
        slingLaunchPoint = new Vector3(slingLaunchObjTransform.position.x, slingLaunchObjTransform.position.y, slingLaunchObjTransform.position.z);
	}
Ejemplo n.º 48
0
    void RpcHitEffect(Vector3 pos, Vector3 normal)
    {
        WeaponGraphics currentWeaponGraphics = weaponManager.GetCurrentGraphics();

        GameObject impactEffect = Instantiate(currentWeaponGraphics.impactEffectPrefab, pos, Quaternion.LookRotation(normal));

        Destroy(impactEffect, currentWeaponGraphics.impactEffectLiftime);
    }
        private void ProcessTileObject(SuperObject superObject, XElement xObject)
        {
            Assert.IsNull(superObject.m_SuperTile);
            Assert.IsNotNull(GlobalTileDatabase, "Cannot process tile objects without a tileset database");

            SuperTile tile       = null;
            var       tileId     = new TileIdMath(superObject.m_TileId);
            int       justTileId = tileId.JustTileId;

            // Are we getting the tile from a template?
            var template = xObject.GetAttributeAs("template", "");

            if (!string.IsNullOrEmpty(template))
            {
                var asset = Importer.RequestAssetAtPath <ObjectTemplate>(template);
                if (asset == null)
                {
                    Importer.ReportError("Template file '{0}' was not found.", template);
                    return;
                }

                tile = asset.m_Tile;
                if (tile == null)
                {
                    Importer.ReportError("Missing tile '{0}' from template '{1}' on tile object '{2}'", justTileId, template, superObject.name);
                    return;
                }
            }

            // Are we getting the tile from our tile database?
            if (tile == null)
            {
                GlobalTileDatabase.TryGetTile(justTileId, out tile);

                if (tile == null)
                {
                    Importer.ReportError("Missing tile '{0}' on tile object '{1}'", justTileId, template, superObject.name);
                    return;
                }
            }

            // Our type may come from the tile as well (this is 'Typed Tiles' in Tiled)
            if (string.IsNullOrEmpty(superObject.m_Type))
            {
                superObject.m_Type = tile.m_Type;
            }

            // Construct the game objects for displaying a single tile
            var  inversePPU = Importer.SuperImportContext.Settings.InversePPU;
            bool flip_h     = tileId.HasHorizontalFlip;
            bool flip_v     = tileId.HasVerticalFlip;

            var scale = Vector3.one;

            scale.x = xObject.GetAttributeAs("width", 1.0f);
            scale.y = xObject.GetAttributeAs("height", 1.0f);

            scale.x /= tile.m_Width;
            scale.y /= tile.m_Height;

            var tileOffset      = new Vector3(tile.m_TileOffsetX * inversePPU, -tile.m_TileOffsetY * inversePPU);
            var translateCenter = new Vector3(tile.m_Width * 0.5f * inversePPU, tile.m_Height * 0.5f * inversePPU);

            // Our root object will contain the translation, rotation, and scale of the tile object
            var goTRS = superObject.gameObject;

            goTRS.transform.localScale = scale;

            // Add another object to handle tile flipping
            // This object will center us into the tile and perform the flips through scaling
            // This object also contains the tile offset in her transform
            var goCF = new GameObject();

            goCF.name = string.Format("{0} (CF)", superObject.m_TiledName);
            goTRS.AddChildWithUniqueName(goCF);

            var toCenter = translateCenter + tileOffset;

            goCF.transform.localPosition = toCenter;
            goCF.transform.localRotation = Quaternion.Euler(0, 0, 0);
            goCF.transform.localScale    = new Vector3(flip_h ? -1 : 1, flip_v ? -1 : 1, 1);

            // Note: We may not want to put the tile "back into place" depending on our coordinate system
            var fromCenter = -toCenter;

            // Isometric maps referece tile objects by bottom center
            if (SuperMap.m_Orientation == MapOrientation.Isometric)
            {
                fromCenter.x -= Importer.SuperImportContext.MakeScalar(tile.m_Width * 0.5f);
            }

            // Add another child, putting our coordinates back into the proper place
            var goTile = new GameObject(superObject.m_TiledName);

            goCF.AddChildWithUniqueName(goTile);
            goTile.transform.localPosition = fromCenter;
            goTile.transform.localRotation = Quaternion.Euler(0, 0, 0);
            goTile.transform.localScale    = Vector3.one;

            // Add the renderer
            var renderer = goTile.AddComponent <SpriteRenderer>();

            renderer.sprite = tile.m_Sprite;
            renderer.color  = new Color(1, 1, 1, superObject.CalculateOpacity());
            Importer.AssignMaterial(renderer);
            Importer.AssignSpriteSorting(renderer);

            // Add the animator if needed
            if (!tile.m_AnimationSprites.IsEmpty())
            {
                var tileAnimator = goTile.AddComponent <TileObjectAnimator>();
                tileAnimator.m_AnimationFramerate = AnimationFramerate;
                tileAnimator.m_AnimationSprites   = tile.m_AnimationSprites;
            }

            // Add any colliders that were set up on the tile in the collision editor
            tile.AddCollidersForTileObject(goTile, Importer.SuperImportContext);

            // Store a reference to our tile object
            superObject.m_SuperTile = tile;
        }
Ejemplo n.º 50
0
 public void UpdateDirection(Vector3 toAlignDirection)
 {
     transform.rotation = Quaternion.LookRotation(toAlignDirection, Vector3.up);
 }
Ejemplo n.º 51
0
		void InitGame ()
		{

			if (PlayerPrefs.HasKey ("highscore")) {
				maxHeightReached = PlayerPrefs.GetFloat ("highscore");
			}
			gameManager = new GameObject ("Game").transform;

			GameObject startingPlatform = Instantiate (platformPiece, new Vector3 (-15, 3.866f, 0f), Quaternion.identity, gameManager) as GameObject;
			GameObject startingCeiling = Instantiate (platformPiece, new Vector3 (-14.376f, -0.634f, 0f), Quaternion.Euler (new Vector3 (0, 0, 90)), gameManager) as GameObject;
			GameObject startingNookWall = Instantiate (platformPiece, new Vector3 (-15, -0.634f, 0f), Quaternion.identity, gameManager) as GameObject;

			startingCeiling.GetComponent<Uncollide> ().mainCharacter = character.GetComponent<MainCharacter> ();
			startingNookWall.GetComponent<Uncollide> ().mainCharacter = character.GetComponent<MainCharacter> ();
			startingPlatform.GetComponent<Uncollide> ().mainCharacter = character.GetComponent<MainCharacter> ();

			Destroy (startingPlatform, 30f);
			Destroy (startingCeiling, 30f);
			Destroy (startingNookWall, 30f);

		}
Ejemplo n.º 52
0
 public void SetQuaternionAttr(string key, Quaternion value)
 {
     Attrs[key] = JsonUtility.ToJson(value);
 }
Ejemplo n.º 53
0
 private void Start()
 {
     m_OriginalRotation = transform.localRotation;
 }
Ejemplo n.º 54
0
 /// <summary>
 /// Gets a deep clone of this instance with its <see cref="Rotation"/> set to the given
 /// value.
 /// </summary>
 /// <param name="rotation">The new <see cref="Rotation"/> for the clone.</param>
 /// <returns>
 /// A deep clone of this instance with its <see cref="Rotation"/> set to the given value.
 /// </returns>
 public IShape <TScalar> GetCloneWithRotation(Quaternion <TScalar> rotation) => this;
Ejemplo n.º 55
0
    private void Update()
    {
        // Do FPS calculation
        frameCount++;
        dt += Time.deltaTime;
        if (dt > 1.0 / fpsDisplayRate)
        {
            fps        = Mathf.Round(frameCount / dt);
            frameCount = 0;
            dt        -= 1.0f / fpsDisplayRate;
        }
        /* Ensure that the cursor is locked into the screen */
        if (Cursor.lockState != CursorLockMode.Locked)
        {
            if (Input.GetButtonDown("Fire1"))
            {
                Cursor.lockState = CursorLockMode.Locked;
            }
        }

        /* Camera rotation stuff, mouse controls this shit */
        rotX += Input.GetAxisRaw("Mouse Y") * xMouseSensitivity * .2f;
        rotY += Input.GetAxisRaw("Mouse X") * yMouseSensitivity * .2f;

        // Clamp the X rotation
        if (rotX < -90)
        {
            rotX = -90;
        }
        else if (rotX > 90)
        {
            rotX = 90;
        }

        this.transform.rotation = Quaternion.Euler(0, rotY, 0);        // Rotates the collider
        playerView.rotation     = Quaternion.Euler(rotX, rotY, 0);     // Rotates the camera



        /* Movement, here's the important part */
        QueueJump();
        if (_controller.isGrounded)
        {
            GroundMove();
        }
        else if (!_controller.isGrounded)
        {
            AirMove();
        }

        // Move the controller
        _controller.Move(playerVelocity * Time.deltaTime);

        /* Calculate top velocity */
        Vector3 udp = playerVelocity;

        udp.y = 0.0f;
        if (udp.magnitude > playerTopVelocity)
        {
            playerTopVelocity = udp.magnitude;
        }

        //Need to move the camera after the player has been moved because otherwise the camera will clip the player if going fast enough and will always be 1 frame behind.
        // Set the camera's position to the transform
        playerView.position = new Vector3(
            transform.position.x,
            transform.position.y + playerViewYOffset,
            transform.position.z);

        if (Input.GetKey(KeyCode.Escape))
        {
            Cursor.lockState = CursorLockMode.None;
            Cursor.visible   = true;
#if UNITY_EDITOR
            UnityEditor.EditorApplication.isPlaying = false;
#else
            Application.Quit();
#endif
        }

        if (transform.position.y < -20)
        {
            transform.position.Set(startPosition.position.x, startPosition.position.y, startPosition.position.z);
            playerVelocity = Vector3.zero;
            _controller.Move(startPosition.position - _controller.transform.position);
            GameState.OnPlayerDeath();
        }
    }
Ejemplo n.º 56
0
    // Update is called once per frame
    void Update()
    {
        if (Time.time > nextSpawnTime)
        {
            float secondsBetweenSpawns = Mathf.Lerp(secondsBetweenSpawnsMinMax.y, secondsBetweenSpawnsMinMax.x, Difficulty.GetDifficultyPercent());
            print(secondsBetweenSpawns);
            nextSpawnTime = Time.time + secondsBetweenSpawns;

            float      spawnAngle    = Random.Range(-spawnAngleMax, spawnAngleMax);
            float      spawnSize     = Random.Range(spawnSizeMinMax.x, spawnSizeMinMax.y);
            Vector2    spawnPosition = new Vector2(Random.Range(-screenHalfSizeWorldUnits.x, screenHalfSizeWorldUnits.x), screenHalfSizeWorldUnits.y + spawnSize);
            GameObject newBlock      = (GameObject)Instantiate(fallingBlockPrefab, spawnPosition, Quaternion.Euler(Vector3.forward * spawnAngle));
            newBlock.transform.localScale = Vector2.one * spawnSize;
        }
    }
Ejemplo n.º 57
0
 public void setDirection(float dir)
 {
     Dir = new Vector3(Mathf.Cos(dir * Mathf.Deg2Rad), Mathf.Sin(dir * Mathf.Deg2Rad), 0);
     transform.rotation = Quaternion.AngleAxis(dir - 90, Vector3.forward);
 }
Ejemplo n.º 58
0
	// Update is called once per frame
	void Update () {
	
				if (Input.GetButtonDown ("Fire2")) {


						objectsNear = Physics2D.CircleCastAll (transform.position, reachRadius, Vector3.forward);
						{
								foreach (RaycastHit2D obj in objectsNear) {
										if (obj.collider.gameObject.GetComponent<bashable> () != null) {
											

												bashableObj = obj.collider.gameObject;
												StartCoroutine ("Counter");
												Time.timeScale = 0;
								
												canBash = true;
												arrow.position = bashableObj.transform.position;
												arrow.Translate (0, 0, 10);

												arrow.gameObject.SetActive (true);
												break;


								
										}
										
								}
						}
				} else if (Input.GetButtonUp ("Fire2") && canBash) {
						Time.timeScale = 1;

						direction = (Camera.main.ScreenToWorldPoint (Input.mousePosition) - bashableObj.transform.position);
						direction.z = 0;
						direction = direction.normalized;

						transform.position = bashableObj.transform.position + direction * 1.2f;

						GetComponent<SimplePlayer0> ().outsideForce = true;
						GetComponent<Rigidbody2D> ().velocity = direction * speed;

						bashableObj.GetComponent<Rigidbody2D> ().velocity = direction * (-1) * bashableObj.GetComponent<Rigidbody2D> ().velocity.magnitude;


						canBash = false;
						arrow.gameObject.SetActive (false);


				} else if (Input.GetButton ("Fire2") && canBash) {


						Vector3 diff = Camera.main.ScreenToWorldPoint(Input.mousePosition) - transform.position;
						diff.Normalize();

						float rot_z = Mathf.Atan2(diff.y, diff.x) * Mathf.Rad2Deg;
						arrow.transform.rotation = Quaternion.Euler(0f, 0f, rot_z );
						Instantiate (effect, bashableObj.transform.position, Quaternion.identity);



				}


	}
		/// <summary>
		/// Reset local position of camera inside of parentRig and resets character's look IK.
		/// </summary>
		private void ResetCamera ()
		{
				lookWeight = Mathf.Lerp (lookWeight, 0.0f, Time.deltaTime * firstPersonLookSpeed);
				transform.localRotation = Quaternion.Lerp (transform.localRotation, Quaternion.identity, Time.deltaTime);
		}
Ejemplo n.º 60
0
/*
    private void FixedUpdate() {
        onSyncWithFixedUpdate = true;
    }

    // Update is called once per frame
    private void Update()
    {
        //This will sync with FixedUpdate with the intention of pausing the game and 
        if(!onSyncWithFixedUpdate){
            return;
        }else{
            onSyncWithFixedUpdate = false;
        }
*/

    // Update is called once per frame
    void FixedUpdate()
    {
        //Return if this player isn't an AI player
        if(!ps.iAmAI){
            curState = AIState.WaitingForTurn;//Just in case something external ends the AI turn
            return;
        }
        switch (curState)
        {
            case(AIState.WaitingForTurn):
                //Change state when player starts turn
                if(ps.isMyTurn){
                    //Debug.Log("starting turn");
                    curState = AIState.Pause;
                    StartCoroutine(ChangeStateIn(AIState.PickingTarget, 2f));
                }
                break;
                
            case(AIState.PickingTarget):
                //Reset List
                targets.Clear(); 
                allEnemiesHealth = 0;
                for(int i = 0; i < GLOBALS.numTeams; i++){
                    //Check if this team is alive, else skip it
                    if(GM.teamsHealth[i] <= 0)
                        continue; //team is dead, move on
                    
                    //Check if this team is the AI team
                    if(ps.teamID == i)
                        continue; //Don't target allies
                    
                    for(int j = 0; j < GLOBALS.teamSize; j++){
                        //Check if this Soldier is alive, else skip it
                        if(GM.soldiersHealth[i,j] <= 0)
                            continue; //Soldier is dead, move on
                        
                        //Add Soldier to possible targets to shoot
                        if(GM.teams[i,j] != null){
                            targets.Add(GM.teams[i,j].transform);
                            //And record it's health for Infinity Gauntlet Calculations
                            allEnemiesHealth += GM.soldiersHealth[i,j];
                        }
                    }
                }

                //We now have all possible targets, now we need to sort them:

                //sort by distance to player ascending
                targets = targets.OrderBy(x => Vector2.Distance(this.transform.position,x.position)).ToList();
                //sort by teams health decending
                targets = targets.OrderBy(x => -GM.teamsHealth[x.GetComponent<PlayerSettings>().teamID]).ToList();
                //sort by soldiers health decending
                targets = targets.OrderBy(x => -x.GetComponent<DamageHandler>().health).ToList();

                curState = AIState.Pause;
                StartCoroutine(ChangeStateIn(AIState.tryingStraightShot, 1f));
                break;

            case(AIState.tryingStraightShot):
                //Debug.Log("tryingStraightShot");
                //Reset target
                target = null; 

                //Loop thru all enemies and chose the first one with direct line of sight
                foreach (Transform tar in targets){
                    //Find direction vector from self to target and normalize it to length 1
                    dir3 = tar.position - weaponContr.weaponPivot.transform.position;
                    dir3.Normalize();
                    dir3.z = 0;

                    //Direct cast from Vector3s to Vector2s
                    origin = weaponContr.weaponPivot.transform.position;
                    direction = dir3;

                    //Send a ray and store the information in hit
                    hit = Physics2D.Raycast(origin + direction*1.5f, direction);
                    //Check if we are hitting a player and that player is not in our team
                    if(hit.transform.tag == "Player" && ps.teamID != hit.transform.GetComponent<PlayerSettings>().teamID){
                        Debug.Log("AI Player says: Found a Target!!");
                        target = hit.transform;
                        break;
                    }
                }
                
                
                if(target == null){//change state TODO
                    Debug.Log("AI Player says: No target in sight");
                    //Set target to be the closest one
                    target = targets.First();

                    //Change state and wait 
                    curState = AIState.Pause;
                    StartCoroutine(ChangeStateIn(AIState.tryingParabolicShot, 1f));
                    //leave state
                    break;
                }
                

                zRotation = CalculateStraightShotAngle(target);

                //Find a default weapon to fall back to
                if(TryWeapon(WeaponCodes.Sniper))               {/*Nothing to do*/}
                else if(TryWeapon(WeaponCodes.Shotgun))         {/*Nothing to do*/}
                else if(TryWeapon(WeaponCodes.Holy_Grenade))    {/*Nothing to do*/}
                else if(TryWeapon(WeaponCodes.Hadouken))        {/*Nothing to do*/}
                else if(TryWeapon(WeaponCodes.BFG9000))         {/*Nothing to do*/}
                else if(TryWeapon(WeaponCodes.Mine))            {/*Nothing to do*/}
                else if(TryWeapon(WeaponCodes.Grenade))         {/*Nothing to do*/}
                else if(TryWeapon(WeaponCodes.Bazooka))         {/*Nothing to do*/}
                else   {TryWeapon(WeaponCodes.Bang_Pistol);}

                //-------Default Weapon has been set---------//

                //If distance between target is small, then prioritize other short range weapons
                if(Vector2.Distance(target.position, transform.position) < 10f){

                    //Try to use Shotgun, else use the Hadouken, else ThunderGun
                    if(TryWeapon(WeaponCodes.Shotgun))          {/*Nothing to do*/}
                    else if(TryWeapon(WeaponCodes.Hadouken))    {/*Nothing to do*/}
                    else if(TryWeapon(WeaponCodes.ThunderGun))  {/*Nothing to do*/}
                    else                                        {/*Keep default weapon*/}

                    //If the angle is good for launching, then prioritize ThunderGun
                    if(zRotation > 30f && zRotation < 60f){
                        TryWeapon(WeaponCodes.ThunderGun);
                    }

                    //If target is in melee range, then prioritize Mjolnir
                    if(Vector2.Distance(target.position, transform.position) < 4f){
                        //Close enough for Mjolnir
                        TryWeapon(WeaponCodes.Mjolnir);
                    }
                }
                
                float rotationOffset = 0f;
                switch (curWeapon)
                {
                    case (int)WeaponCodes.Mjolnir:
                    case (int)WeaponCodes.ThunderGun:
                        rotationOffset = 7f;
                        break;

                    case (int)WeaponCodes.Hadouken:
                        rotationOffset = 1.5f;
                        break;

                    case (int)WeaponCodes.Mine:
                    case (int)WeaponCodes.Bazooka:
                    case (int)WeaponCodes.Grenade:
                    case (int)WeaponCodes.Holy_Grenade:
                    case (int)WeaponCodes.Teleport_Grenade:
                        //**************TODO********************
                        break;
                    default:
                        break;
                }
                
                if(Mathf.Abs(zRotation) < 90f){
                    zRotation += rotationOffset;//raise weapon x degrees up
                }else{
                    zRotation -= rotationOffset;//raise weapon x degrees up
                }

                //Change state and wait 
                curState = AIState.Pause;
                StartCoroutine(ChangeStateIn(AIState.Aiming, 1f));
                break;

            case(AIState.tryingParabolicShot):
                //Debug.Log("tryingParabolicShot");
                
                //This is for ThunderGun and sets yDiff and xDiff 
                zRotation = CalculateStraightShotAngle(target);
                angle_1 = angle_2 = 0f;
                
                if(TryWeapon(WeaponCodes.ThunderGun) && Vector2.Distance(target.position, transform.position) < 10f && zRotation > 10f && zRotation < 70f)
                {/*In ThunderGun range and optimal angle range*/}
                else if(TryWeapon(WeaponCodes.BFG9000) && targets.Last().GetComponent<DamageHandler>().health < 50)
                {/*The target has low health*/
                    zRotation = CalculateStraightShotAngle(targets.Last());
                }
                else if(TryWeapon(WeaponCodes.Infinity_Gauntlet) && (dh.health < allEnemiesHealth/2f) && dh.health != GM.teamsHealth[ps.teamID])
                {/*AI has low health and is not the last man of its team*/}
                else if(TryWeapon(WeaponCodes.PlaneBomber) || TryWeapon(WeaponCodes.Plane_Nuke))
                {
                    //Sort list for farthest and highest targets
                    targets = targets.OrderBy(x => -(x.position.y * 100 + Vector2.Distance(this.transform.position,x.position))).ToList();
                    target = targets.First();
                }
                else if(TryWeapon(WeaponCodes.Homing_Bazooka))
                {
                    zRotation = 90;
                    weaponScript.fireTriggered = true;
                }
                else{
                    if(CalculateParabolicShotAngles(target, WeaponCodes.Bazooka) && TryWeapon(WeaponCodes.Bazooka) && rand.NextDouble() > 0.5)      {/*Nothing to do*/}
                    else if(CalculateParabolicShotAngles(target, WeaponCodes.Mine) && TryWeapon(WeaponCodes.Mine))                                  {/*Nothing to do*/}
                    else if(CalculateParabolicShotAngles(target, WeaponCodes.Holy_Grenade) && TryWeapon(WeaponCodes.Holy_Grenade))                  {/*Nothing to do*/}
                    else if(CalculateParabolicShotAngles(target, WeaponCodes.Grenade) && TryWeapon(WeaponCodes.Grenade) && rand.NextDouble() > 0.5) {/*Nothing to do*/}
                    else if(CalculateParabolicShotAngles(target, WeaponCodes.Teleport_Grenade) && TryWeapon(WeaponCodes.Teleport_Grenade))          {/*Nothing to do*/}
                    else{TryWeapon(WeaponCodes.Bang_Pistol);}

                    zRotation = angle_1;
                }
                
                //Change state and wait 
                curState = AIState.Pause;
                StartCoroutine(ChangeStateIn(AIState.Aiming, 1f));
                break;

            case(AIState.Aiming):
                //Check if gun is close to the correct angle
                if(Mathf.Abs(currentRotation - (360 + zRotation) % 360) < 5f){
                    //Debug.Log("Finished Aiming");
                    weaponContr.AimTo(zRotation, xDiff);
                    curState = AIState.Pause;
                    StartCoroutine(ChangeStateIn(AIState.Shooting, 1f));
                    break;
                }

                //Rotate Weapon
                currentRotation = (currentRotation + 4) % 360;
                
                if (Mathf.Cos(currentRotation * Mathf.Deg2Rad) > 0)
                {
                    //We should be facing right
                    transform.eulerAngles = new Vector3(0, 0, 0);
                    ps.FlipName(false);
                    //Rotate gun to point at mouse
                    weaponContr.weaponPivot.rotation = Quaternion.Euler(0, 0, currentRotation);
                }
                else
                {
                    //We should be facing left
                    transform.eulerAngles = new Vector3(0, 180, 0);
                    ps.FlipName(true);
                    //Rotate gun to point at mouse but gun is upside down, so flip 180 on x
                    //And compansate fliping x by inverting z rotation
                    weaponContr.weaponPivot.rotation = Quaternion.Euler(180, 0, -currentRotation);
                }

                break;

            case(AIState.Shooting):
                //Debug.Log("Shooting " + curWeapon);
                curState = AIState.Pause;
                StartCoroutine(ChangeStateIn(AIState.WaitingForTurn, 1f));
                weaponScript.fireTriggered = true;
                break;

            case(AIState.Moving):
                //***************************TODO**************************
                break;

            case(AIState.Pause):
                //This is a dead state meant for the AI to just wait for some time
                //This state should only be called along with the coroutine ChangeStateIn()
                break;

            default:
                Debug.LogError("Invalid State reached... but HOW??!!");
                break;
        }
    }