예제 #1
1
		/// <summary>
		/// Pins the effector to the animated position of it's bone.
		/// </summary>
		public void PinToBone(float positionWeight, float rotationWeight) {
			position = bone.position;
			this.positionWeight = Mathf.Clamp(positionWeight, 0f, 1f);

			rotation = bone.rotation;
			this.rotationWeight = Mathf.Clamp(rotationWeight, 0f, 1f);
		}
예제 #2
1
        private void UpdateGravity()
        {
            _GravityDirection = GetGravityDirection();

            _Rigidbody.AddForce(_GravityDirection * Gravity, ForceMode2D.Force);
            _TargetRotation = Quaternion.Euler(new Vector3(0f, 0f, VectorUtils.GetAngle(Vector2.down, _GravityDirection)));
        }
예제 #3
1
        public void Start()
        {
            key = GameObject.Find("Key").gameObject;

            dupMarker = Quaternion.Euler(0, transform.rotation.eulerAngles.y + 45, 0);
            originMarker = Quaternion.Euler(0, originDoor.transform.rotation.eulerAngles.y - 45, 0);
        }
예제 #4
1
 public DrawGridParameters PrepareGridRender(Camera camera, Vector3 pivot, Quaternion rotation, float size, bool orthoMode, bool gridVisible)
 {
   bool flag1 = false;
   bool flag2 = false;
   bool flag3 = false;
   if (gridVisible)
   {
     if (orthoMode)
     {
       Vector3 vector3 = rotation * Vector3.forward;
       if ((double) Mathf.Abs(vector3.y) > 0.200000002980232)
         flag2 = true;
       else if (vector3 == Vector3.left || vector3 == Vector3.right)
         flag1 = true;
       else if (vector3 == Vector3.forward || vector3 == Vector3.back)
         flag3 = true;
     }
     else
       flag2 = true;
   }
   this.xGrid.target = flag1;
   this.yGrid.target = flag2;
   this.zGrid.target = flag3;
   DrawGridParameters drawGridParameters;
   drawGridParameters.pivot = pivot;
   drawGridParameters.color = (Color) SceneViewGrid.kViewGridColor;
   drawGridParameters.size = size;
   drawGridParameters.alphaX = this.xGrid.faded;
   drawGridParameters.alphaY = this.yGrid.faded;
   drawGridParameters.alphaZ = this.zGrid.faded;
   return drawGridParameters;
 }
예제 #5
1
파일: DebugUtils.cs 프로젝트: siwenRen/Wolf
		public static void DrawDoubleCircle(Vector3 origin, Quaternion rotation, float radius1, float radius2, int pieceCount, Color color)
		{
			if (3 > pieceCount)
			{
				return;
			}
			if (0 >= radius1 || 0 >= radius2)
			{
				return;
			}
			
			float pieceAngle = 360.0f / pieceCount;
			
			Vector3 p0_1 = origin + rotation * Vector3.forward * radius1;
			Vector3 p0_2 = origin + rotation * Vector3.forward * radius2;
			Vector3 p1_1 = p0_1;
			Vector3 p1_2 = p0_2;
			for (int i = 0; i < pieceCount-1; ++i)
			{
				var r = Quaternion.Euler(0, pieceAngle*(i+1), 0);
				Vector3 p2_1 = origin + rotation * (r * Vector3.forward * radius1);
				Vector3 p2_2 = origin + rotation * (r * Vector3.forward * radius2);
				Debug.DrawLine(p1_1, p2_1, color);
				Debug.DrawLine(p1_2, p2_2, color);
				Debug.DrawLine(p2_1, p2_2, color);
				
				p1_1 = p2_1;
				p1_2 = p2_2;
			}
			Debug.DrawLine(p0_1, p1_1, color);
			Debug.DrawLine(p0_1, p0_2, color);
		}
예제 #6
1
파일: DebugUtils.cs 프로젝트: siwenRen/Wolf
		public static void DrawCircle(Vector3 origin, Quaternion rotation, float radius, int pieceCount, Color color)
		{
			if (3 > pieceCount)
			{
				return;
			}
			if (0 >= radius)
			{
				return;
			}

			float pieceAngle = 360.0f / pieceCount;

			Vector3 p0 = origin + rotation * Vector3.forward * radius;
			Vector3 p1 = p0;
			for (int i = 0; i < pieceCount-1; ++i)
			{
				var r = Quaternion.Euler(0, pieceAngle*(i+1), 0);
				Vector3 p2 = origin + rotation * (r * Vector3.forward * radius);
				Debug.DrawLine(p1, p2, color);

				p1 = p2;
			}
			Debug.DrawLine(p0, p1, color);
		}
예제 #7
1
        // Update is called once per frame
        void Update()
        {
            if (target.gameObject == null) {

                if (_statusIndicators.gameObject != null) {
                    _statusIndicators.SetDirectors ();
                    Destroy (this.gameObject);
                }
                return;
            }

            _direction = target.transform.position - transform.position;
            //_direction.z = 0f;

            _lookRotation = Quaternion.LookRotation (_direction, Vector3.back);

            Quaternion rotateTo = Quaternion.Slerp (transform.rotation, _lookRotation, RotationSpeed);
            rotateTo.x = 0f;
            rotateTo.y = 0f;
            this.transform.rotation = rotateTo;

            if (_direction.magnitude > minDist) {
                newAlpha = 1 - _direction.magnitude / maxDist;
            } else {
                newAlpha = _direction.magnitude / minDist - 0.4f;
            }

            image.color = new Color (image.color.r, image.color.g, image.color.b, newAlpha);
            //Debug.Log("Normalized magnitude: " + (int)_direction.magnitude + " New Alpa: " +newAlpha );
        }
 public Quat(Quaternion _quat)
 {
     this.x = _quat.x;
     this.y = _quat.y;
     this.z = _quat.z;
     this.w = _quat.w;
 }
예제 #9
1
        // Rotate this target towards a position
        public void RotateTo(Vector3 position)
        {
            if (pivot == null) return;

            if (pivot != lastPivot) {
                defaultLocalRotation = pivot.localRotation;
                lastPivot = pivot;
            }

            // Rotate to the default local rotation
            pivot.localRotation = defaultLocalRotation;

            // Twisting around the twist axis
            if (twistWeight > 0f) {
                Vector3 targetTangent = transform.position - pivot.position;
                Vector3 n = pivot.rotation * twistAxis;
                Vector3 normal = n;
                Vector3.OrthoNormalize(ref normal, ref targetTangent);

                normal = n;
                Vector3 direction = position - pivot.position;
                Vector3.OrthoNormalize(ref normal, ref direction);

                Quaternion q = QuaTools.FromToAroundAxis(targetTangent, direction, n);
                pivot.rotation = Quaternion.Lerp(Quaternion.identity, q, twistWeight) * pivot.rotation;
            }

            // Swinging freely
            if (swingWeight > 0f) {
                Quaternion s = Quaternion.FromToRotation(transform.position - pivot.position, position - pivot.position);
                pivot.rotation = Quaternion.Lerp(Quaternion.identity, s, swingWeight) * pivot.rotation;
            }
        }
예제 #10
1
 public void Write(Quaternion qua)
 {
     writer.Write(qua.x);
     writer.Write(qua.y);
     writer.Write(qua.z);
     writer.Write(qua.w);
 }
예제 #11
1
        void Start()
        {
            _jesus = transform.parent.parent.GetComponent<Jesus>();

            IsVisible = true;
            _targetRotation = _jesus.PickNewTarget();
        }
        void Start()
        {
            m_Cam = GetComponent<Camera>();
            m_OriginalRotation = transform.localRotation;

            this.UpdateAsObservable()
                .Where(_ => GameState.Instance.GameStateReactiveProperty.Value == GameStateEnum.Countdown ||
                            GameState.Instance.GameStateReactiveProperty.Value == GameStateEnum.GameUpdate)
                .Select(_ =>
                {
                    var playerPos = PlayerManager.Instance.GetAlivePlayers()
                        .Select(x => x.transform.position);

                    var _x = playerPos.Average(x => x.x);
                    var _y = playerPos.Average(x => x.y);
                    var _z = playerPos.Average(x => x.z);

                    tergetPos = new Vector3(_x, _y, _z);
                    return tergetPos;

                }).DelayFrame(3)
                .Subscribe(target =>
                {
                    var campos = tergetPos + m_defaultPosition;
                    transform.position = Vector3.Lerp(this.transform.position, campos, Time.deltaTime * 5.0f);
             //       transform.LookAt(target - this.transform.position);
                });

        }
예제 #13
1
		public void Write(Quaternion quaternion)
		{
			Write(quaternion.x);
			Write(quaternion.y);
			Write(quaternion.z);
			Write(quaternion.w);
		}
		/*
		 * Apply the swing rotation limits
		 * */
		public Quaternion LimitSwing(Quaternion rotation) {
			if (axis == Vector3.zero) return rotation; // Ignore with zero axes
			if (rotation == Quaternion.identity) return rotation; // Assuming initial rotation is in the reachable area
			
			// Get the rotation angle orthogonal to Axis
			Vector3 swingAxis = rotation * axis;
			float angle = GetOrthogonalAngle(swingAxis, secondaryAxis, axis);
			
			// Convert angle from 180 to 360 degrees representation
			float dot = Vector3.Dot(swingAxis, crossAxis);
			if (dot < 0) angle = 180 + (180 - angle);
			
			// Evaluate the limit for this angle
			float limit = spline.Evaluate(angle);
			
			// Get the limited swing axis
			Quaternion swingRotation = Quaternion.FromToRotation(axis, swingAxis);
			Quaternion limitedSwingRotation = Quaternion.RotateTowards(Quaternion.identity, swingRotation, limit);
			
			// Rotation from current(illegal) swing rotation to the limited(legal) swing rotation
			Quaternion toLimits = Quaternion.FromToRotation(swingAxis, limitedSwingRotation * axis);
			
			// Subtract the illegal rotation
			return toLimits * rotation;
		}
		private ObscuredQuaternion(RawEncryptedQuaternion value)
		{
			currentCryptoKey = cryptoKey;
			hiddenValue = value;
			fakeValue = initialFakeValue;
			inited = true;
		}
		/*
		 * Limits the rotation in the local space of this instance's Transform.
		 * */
		protected override Quaternion LimitRotation(Quaternion rotation) {		
			// Subtracting off-limits swing
			Quaternion swing = LimitSwing(rotation);
			
			// Apply twist limits
			return LimitTwist(swing, axis, secondaryAxis, twistLimit);
		}
예제 #17
0
 // Use this for initialization
 void Awake()
 {
     palm = GetComponent<HandModel>().palm;
       startingPalmPosition = palm.localPosition;
       startingOrientation = palm.localRotation;
       startingScale = transform.localScale;
 }
예제 #18
0
 private void Read(out Quaternion qua)
 {
     qua.x = reader.ReadSingle();
     qua.y = reader.ReadSingle();
     qua.z = reader.ReadSingle();
     qua.w = reader.ReadSingle();
 }
        public void OnNetworkData(double time, Vector3 position, Quaternion rotation)
        {
            // Shift the buffer sideways, deleting state 20
            for (int i = m_BufferedState.Length - 1; i >= 1; i--)
            {
                m_BufferedState[i] = m_BufferedState[i - 1];
            }

            // Record current state in slot 0
            State state = new State();
            state.timestamp = time;
            state.pos = position;
            state.rot = rotation;

            m_BufferedState[0] = state;

            // Update used slot count, however never exceed the buffer size
            // Slots aren't actually freed so this just makes sure the buffer is
            // filled up and that uninitalized slots aren't used.
            m_TimestampCount = Mathf.Min(m_TimestampCount + 1, m_BufferedState.Length);

            // Check if states are in order, if it is inconsistent you could reshuffel or
            // drop the out-of-order state. Nothing is done here
            for (int i = 0; i < m_TimestampCount - 1; i++)
            {
                if (m_BufferedState[i].timestamp < m_BufferedState[i + 1].timestamp)
                    Debug.Log("State inconsistent");
            }
        }
예제 #20
0
 public SerializedQuaternion(Quaternion q)
 {
     x = q.x;
     y = q.y;
     z = q.z;
     w = q.w;
 }
예제 #21
0
 public static Quaternion LoadQuaternion(JsonTextReader reader)
 {
     Quaternion rotation = new Quaternion(0, 0, 0, 0);
     if (reader == null) return rotation;
     string currVal = "";
     while (reader.Read())
     {
         if (reader.Value != null)
         {
             if (reader.TokenType == JsonToken.PropertyName) currVal = (string)reader.Value;
             else
             {
                 switch (currVal)
                 {
                     case "x": rotation.x = (float)(double)reader.Value; break;
                     case "y": rotation.y = (float)(double)reader.Value; break;
                     case "z": rotation.z = (float)(double)reader.Value; break;
                     case "w": rotation.w = (float)(double)reader.Value; break;
                     default: break;
                 }
             }
         }
         else if (reader.TokenType == JsonToken.EndObject) return rotation;
     }
     return rotation;
 }
예제 #22
0
        void DoSmoothLookAt()
        {
            var go = Fsm.GetOwnerDefaultTarget(gameObject);
            if (go == null)
            {
                return;
            }

            var goTarget = targetObject.Value;
            if (goTarget == null && targetPosition.IsNone)
            {
                return;
            }

            // re-initialize if game object has changed

            if (previousGo != go)
            {
                lastRotation = go.transform.rotation;
                desiredRotation = lastRotation;
                previousGo = go;
            }

            // desired look at position

            Vector3 lookAtPos;
            if (goTarget != null)
            {
                lookAtPos = !targetPosition.IsNone ?
                    goTarget.transform.TransformPoint(targetPosition.Value) :
                    goTarget.transform.position;
            }
            else
            {
                lookAtPos = targetPosition.Value;
            }

            if (keepVertical.Value)
            {
                lookAtPos.y = go.transform.position.y;
            }

            // smooth look at

            var diff = lookAtPos - go.transform.position;
            if (diff.sqrMagnitude > 0)
            {
                desiredRotation = Quaternion.LookRotation(diff, upVector.IsNone ? Vector3.up : upVector.Value);
            }

            lastRotation = Quaternion.Slerp(lastRotation, desiredRotation, speed.Value * Time.deltaTime);
            go.transform.rotation = lastRotation;

            // debug line to target

            if (debug.Value)
            {
                Debug.DrawLine(go.transform.position, lookAtPos, Color.grey);
            }
        }
예제 #23
0
 private void UpdateRotation(Quaternion currentRotation, float currentDegrees)
 {
     float closerDegress = GetCloserDegrees (currentDegrees);
     Vector3 newAngles = new Vector3 (currentRotation.eulerAngles.x,closerDegress,currentRotation.eulerAngles.z);
     Quaternion newRot = Quaternion.Euler (newAngles);
     myTransform.localRotation = Quaternion.Lerp (currentRotation,newRot,Time.deltaTime * currentSpeed);
 }
예제 #24
0
		public GravityObject (Vector2 position, Quaternion rotation, ObjectTypes type)
			: this()
		{
			Position = position;
			Rotation = rotation;
			Type = type;
		}
예제 #25
0
 public static Quaternion Step(Quaternion current, Quaternion target, float omega)
 {
     if (current == target)
         return target;
     else
         return Quaternion.Lerp(target, current, Mathf.Exp(-omega * Time.deltaTime));
 }
예제 #26
0
파일: Utils.cs 프로젝트: ElasticRaven/KOS
 public static bool IsValidRotation(Quaternion quaternion)
 {
     return IsValidNumber(quaternion.x) &&
            IsValidNumber(quaternion.y) &&
            IsValidNumber(quaternion.z) &&
            IsValidNumber(quaternion.w);
 }
예제 #27
0
        protected virtual void Set(Part p, ReentrySimulation.SimCurves _simCurves)
        {
            Rigidbody rigidbody = p.rb;

            totalMass = rigidbody == null ? 0 : rigidbody.mass; // TODO : check if we need to use this or the one without the childMass
            shieldedFromAirstream = p.ShieldedFromAirstream;

            noDrag = rigidbody == null && !PhysicsGlobals.ApplyDragToNonPhysicsParts;
            hasLiftModule = p.hasLiftModule;
            bodyLiftMultiplier = p.bodyLiftMultiplier * PhysicsGlobals.BodyLiftMultiplier;

            simCurves = _simCurves;

            cubes = new DragCubeList();
            CopyDragCubesList(p.DragCubes, cubes);

            // Rotation to convert the vessel space vesselVelocity to the part space vesselVelocity
            vesselToPart = Quaternion.LookRotation(p.vessel.GetTransform().InverseTransformDirection(p.transform.forward), p.vessel.GetTransform().InverseTransformDirection(p.transform.up)).Inverse();

            //DragCubeMultiplier = PhysicsGlobals.DragCubeMultiplier;
            //DragMultiplier = PhysicsGlobals.DragMultiplier;


            //if (p.dragModel != Part.DragModel.CUBE)
            //    MechJebCore.print(p.name + " " + p.dragModel);

            //oPart = p;

        }
예제 #28
0
파일: MouseLook.cs 프로젝트: Eibis/GGJ2016
        public void LookRotation(Transform character, Transform camera)
        {
            float yRot = CrossPlatformInputManager.GetAxis("Mouse X") * XSensitivity;
            float xRot = CrossPlatformInputManager.GetAxis("Mouse Y") * YSensitivity;

            if (yRot == 0)
                yRot = CrossPlatformInputManager.GetAxis("Right_X") * XSensitivity;

            if (xRot == 0)
                xRot = CrossPlatformInputManager.GetAxis("Right_Y") * YSensitivity;

            m_CharacterTargetRot *= Quaternion.Euler (0f, yRot, 0f);
            m_CameraTargetRot *= Quaternion.Euler (-xRot, 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;
            }

            UpdateCursorLock();
        }
예제 #29
0
        public static GameObject ActivateObject(string objectName, Vector3 pos, Quaternion rotation)
        {
            ObjectPool pool = Instance.pools.FirstOrDefault(t => t.ObjectName == objectName);
            if (pool == null) return null;

            return pool.GetObject(pos, rotation);
        }
        public static GameObject Create(GameObject prefab, Vector3 pos, Quaternion rot, Transform parent)
        {
            if (parent == null) return Create(prefab, pos, rot);

            prefab.AddOrGetComponent<EarlyParentSetter>().Init(parent);
            return UnityEngine.Object.Instantiate(prefab, pos, rot) as GameObject;
        }
예제 #31
0
    void FixedUpdate()
    {
        if (canCreate)
        {
            if (Input.GetMouseButtonUp(0))
            {
                Vector3 mousePos  = cam.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, 100.0f));
                Vector3 direction = mousePos - cam.transform.position;

                RaycastHit hit;

                if (Physics.Raycast(cam.transform.position, direction, out hit, 100.0f))
                {
                    Debug.DrawLine(cam.transform.position, hit.point, Color.green, 0.5f);

                    GameObject obj = cube;
                    switch (obs)
                    {
                    case Obstacles.Cube:
                        obj = cube;
                        break;

                    case Obstacles.Cylinder:
                        obj = cylinder;
                        break;

                    case Obstacles.Sphere:
                        obj = sphere;
                        break;
                    }

                    Bounds b      = obj.GetComponent <MeshFilter>().sharedMesh.bounds;
                    float  height = b.size.y;

                    Vector3 pos = new Vector3(hit.point.x, hit.point.y + (height / 2.0f), hit.point.z);

                    lastObj = Instantiate(obj, pos, Quaternion.Euler(Vector3.zero));

                    canCreate = false;
                }
                else
                {
                    Debug.DrawLine(cam.transform.position, mousePos, Color.red, 0.5f);
                }
            }
        }
        else
        {
            if (Input.GetMouseButtonUp(1))
            {
                Vector3 mousePos  = cam.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, 100.0f));
                Vector3 direction = mousePos - cam.transform.position;

                RaycastHit hit;

                if (Physics.Raycast(cam.transform.position, direction, out hit, 100.0f))
                {
                    Debug.DrawLine(cam.transform.position, hit.point, Color.green, 0.5f);

                    Destroy(hit.collider.gameObject);
                }
                else
                {
                    Debug.DrawLine(cam.transform.position, mousePos, Color.red, 0.5f);
                }
            }
        }
    }
예제 #32
0
 public override object spawnTitanHook(int rate, UnityEngine.Vector3 position, UnityEngine.Quaternion rotation, bool punk)
 {
     return(null);//this.main.getSpawnController().spawnTitanHook(rate, position, rotation, punk);
 }
예제 #33
0
        /** Updates graphs with a created GUO.
         * Creates a Pathfinding.GraphUpdateObject with a Pathfinding.GraphUpdateShape
         * representing the polygon of this object and update all graphs using AstarPath.UpdateGraphs.
         * This will not update graphs immediately. See AstarPath.UpdateGraph for more info.
         */
        public void Apply()
        {
            if (AstarPath.active == null)
            {
                Debug.LogError("There is no AstarPath object in the scene", this);
                return;
            }

            GraphUpdateObject guo;

            if (points == null || points.Length == 0)
            {
                var polygonCollider = GetComponent <PolygonCollider2D>();
                if (polygonCollider != null)
                {
                    var       points2D = polygonCollider.points;
                    Vector3[] pts      = new Vector3[points2D.Length];
                    for (int i = 0; i < pts.Length; i++)
                    {
                        var p = points2D[i] + polygonCollider.offset;
                        pts[i] = new Vector3(p.x, 0, p.y);
                    }

                    var mat   = transform.localToWorldMatrix * Matrix4x4.TRS(Vector3.zero, Quaternion.Euler(-90, 0, 0), Vector3.one);
                    var shape = new GraphUpdateShape(points, convex, mat, minBoundsHeight);
                    guo       = new GraphUpdateObject(GetBounds());
                    guo.shape = shape;
                }
                else
                {
                    var bounds = GetBounds();
                    if (bounds.center == Vector3.zero && bounds.size == Vector3.zero)
                    {
                        Debug.LogError("Cannot apply GraphUpdateScene, no points defined and no renderer or collider attached", this);
                        return;
                    }

                    guo = new GraphUpdateObject(bounds);
                }
            }
            else
            {
                GraphUpdateShape shape;
                if (legacyMode && !legacyUseWorldSpace)
                {
                    // Used for compatibility with older versions
                    var worldPoints = new Vector3[points.Length];
                    for (int i = 0; i < points.Length; i++)
                    {
                        worldPoints[i] = transform.TransformPoint(points[i]);
                    }
                    shape = new GraphUpdateShape(worldPoints, convex, Matrix4x4.identity, minBoundsHeight);
                }
                else
                {
                    shape = new GraphUpdateShape(points, convex, legacyMode && legacyUseWorldSpace ? Matrix4x4.identity : transform.localToWorldMatrix, minBoundsHeight);
                }
                var bounds = shape.GetBounds();
                guo       = new GraphUpdateObject(bounds);
                guo.shape = shape;
            }

            firstApplied = true;

            guo.modifyWalkability     = modifyWalkability;
            guo.setWalkability        = setWalkability;
            guo.addPenalty            = penaltyDelta;
            guo.updatePhysics         = updatePhysics;
            guo.updateErosion         = updateErosion;
            guo.resetPenaltyOnPhysics = resetPenaltyOnPhysics;

            guo.modifyTag = modifyTag;
            guo.setTag    = setTag;
        }
예제 #34
0
 public static Improbable.Transform.Quaternion ToImprobableQuaternion(this Quaternion quaternion)
 {
     return(new Improbable.Transform.Quaternion(quaternion.w, quaternion.x, quaternion.y,
                                                quaternion.z));
 }
예제 #35
0
 public UnityEngine.Quaternion Call()
 {
     func.Call();
     UnityEngine.Quaternion ret = func.CheckQuaternion();
     return(ret);
 }
예제 #36
0
 public QuaternionStamped()
 {
     this.header     = new std_msgs.Header();
     this.quaternion = new UnityEngine.Quaternion();
 }
예제 #37
0
 public QuaternionStamped(std_msgs.Header header, UnityEngine.Quaternion quaternion)
 {
     this.header     = header;
     this.quaternion = quaternion;
 }
    void Update()
    {
        if (pauseUpdating)
        {
            return;
        }

        CalculateGuidingArrowPosition();

        if (Input.touchCount <= 0)
        {
            return;
        }

        if (Input.touchCount == 1)
        {
            Touch touch = Input.GetTouch(0);

            if (touch.phase.Equals(TouchPhase.Began))
            {
                // store the first finger position
                startingTouchPosition = touch.position;
            }
            else if (touch.phase.Equals((TouchPhase.Moved)))
            {
                Vector2 touchDifferenceVector = touch.position - startingTouchPosition;

                if (adjustingMagnitude)
                {
                    _forceValueText.gameObject.SetActive(true);
                    // Y value is passed as X, to change magnitude
                    float   adjustableValue = 2 * touchDifferenceVector.y / Screen.height;
                    Vector2 yDifference     = new Vector2(adjustableValue, 0);

                    for (int i = 0; i < directionRenderers.Length; i++)
                    {
                        AdjustLineRendererPosition(directionRenderers[i], _movableObjectRigidbodies[i], yDifference, Vector2.right, out _forceToObjects[i]);
                    }


//                    if (_secondaryMovableObject) AdjustLineRendererPosition(_secondaryObjectLineRenderer, yDifference, Vector2.right, out _forceToObject);


                    _forceValueText.text = "Force: " + (_forceToObjects[0].x * pushForce).ToString("F1") + " N";
                }
                else if (adjustingDirection)
                {
                    for (int i = 0; i < movableObjects.Length; i++)
                    {
                        movableObjects[i].Rotate(Vector3.up, touchDifferenceVector.x / 2);
                    }

                    lastAdjustedRotation = movableObjects[0].rotation;
                }


                if (touchDifferenceVector.magnitude > touchDelta && !adjustingSet)
                {
                    if (Mathf.Abs(touchDifferenceVector.x) > Mathf.Abs(touchDifferenceVector.y))
                    {
                        adjustingDirection = true;
                        adjustingMagnitude = false;
                    }
                    else
                    {
                        adjustingDirection = false;
                        adjustingMagnitude = true;
                    }

                    adjustingSet = false;
                }

                startingTouchPosition = touch.position;
            }
            else if (touch.phase.Equals(TouchPhase.Ended))
            {
                adjustingSet       = false;
                adjustingMagnitude = false;
                adjustingDirection = false;
                _forceValueText.gameObject.SetActive(false);
            }
        }
    }
예제 #39
0
 private void GravRotate(Transform body, Quaternion targetRot)
 {
     //Sets the body rotation
     body.rotation = Quaternion.Slerp(body.rotation, targetRot, Time.deltaTime * smooth);
 }
    static int Instantiate(IntPtr L)
    {
        IntPtr L0 = LuaException.L;

        try
        {
            ++LuaException.InstantiateCount;
            LuaException.L = L;
            int count = LuaDLL.lua_gettop(L);

            if (count == 1)
            {
                UnityEngine.Object arg0 = (UnityEngine.Object)ToLua.CheckObject <UnityEngine.Object>(L, 1);
                UnityEngine.Object o    = UnityEngine.Object.Instantiate(arg0);

                if (LuaDLL.lua_toboolean(L, LuaDLL.lua_upvalueindex(1)))
                {
                    string error = LuaDLL.lua_tostring(L, -1);
                    LuaDLL.lua_pop(L, 1);
                    throw new LuaException(error, LuaException.GetLastError());
                }
                else
                {
                    ToLua.Push(L, o);
                }

                LuaException.L = L0;
                --LuaException.InstantiateCount;
                return(1);
            }
#if UNITY_5_4_OR_NEWER
            else if (count == 2)
            {
                UnityEngine.Object    arg0 = (UnityEngine.Object)ToLua.CheckObject <UnityEngine.Object>(L, 1);
                UnityEngine.Transform arg1 = (UnityEngine.Transform)ToLua.CheckObject <UnityEngine.Transform>(L, 2);
                UnityEngine.Object    o    = UnityEngine.Object.Instantiate(arg0, arg1);

                if (LuaDLL.lua_toboolean(L, LuaDLL.lua_upvalueindex(1)))
                {
                    string error = LuaDLL.lua_tostring(L, -1);
                    LuaDLL.lua_pop(L, 1);
                    throw new LuaException(error, LuaException.GetLastError());
                }
                else
                {
                    ToLua.Push(L, o);
                }

                LuaException.L = L0;
                --LuaException.InstantiateCount;
                return(1);
            }
#endif
            else if (count == 3 && TypeChecker.CheckTypes <UnityEngine.Vector3, UnityEngine.Quaternion>(L, 2))
            {
                UnityEngine.Object     arg0 = (UnityEngine.Object)ToLua.CheckObject <UnityEngine.Object>(L, 1);
                UnityEngine.Vector3    arg1 = ToLua.ToVector3(L, 2);
                UnityEngine.Quaternion arg2 = ToLua.ToQuaternion(L, 3);
                UnityEngine.Object     o    = UnityEngine.Object.Instantiate(arg0, arg1, arg2);

                if (LuaDLL.lua_toboolean(L, LuaDLL.lua_upvalueindex(1)))
                {
                    string error = LuaDLL.lua_tostring(L, -1);
                    LuaDLL.lua_pop(L, 1);
                    throw new LuaException(error, LuaException.GetLastError());
                }
                else
                {
                    ToLua.Push(L, o);
                }

                LuaException.L = L0;
                --LuaException.InstantiateCount;
                return(1);
            }
#if UNITY_5_4_OR_NEWER
            else if (count == 3 && TypeChecker.CheckTypes <UnityEngine.Transform, bool>(L, 2))
            {
                UnityEngine.Object    arg0 = (UnityEngine.Object)ToLua.CheckObject <UnityEngine.Object>(L, 1);
                UnityEngine.Transform arg1 = (UnityEngine.Transform)ToLua.ToObject(L, 2);
                bool arg2            = LuaDLL.lua_toboolean(L, 3);
                UnityEngine.Object o = UnityEngine.Object.Instantiate(arg0, arg1, arg2);

                if (LuaDLL.lua_toboolean(L, LuaDLL.lua_upvalueindex(1)))
                {
                    string error = LuaDLL.lua_tostring(L, -1);
                    LuaDLL.lua_pop(L, 1);
                    throw new LuaException(error, LuaException.GetLastError());
                }
                else
                {
                    ToLua.Push(L, o);
                }

                LuaException.L = L0;
                --LuaException.InstantiateCount;
                return(1);
            }
            else if (count == 4)
            {
                UnityEngine.Object     arg0 = (UnityEngine.Object)ToLua.CheckObject <UnityEngine.Object>(L, 1);
                UnityEngine.Vector3    arg1 = ToLua.CheckVector3(L, 2);
                UnityEngine.Quaternion arg2 = ToLua.CheckQuaternion(L, 3);
                UnityEngine.Transform  arg3 = (UnityEngine.Transform)ToLua.CheckObject <UnityEngine.Transform>(L, 4);
                UnityEngine.Object     o    = UnityEngine.Object.Instantiate(arg0, arg1, arg2, arg3);

                if (LuaDLL.lua_toboolean(L, LuaDLL.lua_upvalueindex(1)))
                {
                    string error = LuaDLL.lua_tostring(L, -1);
                    LuaDLL.lua_pop(L, 1);
                    throw new LuaException(error, LuaException.GetLastError());
                }
                else
                {
                    ToLua.Push(L, o);
                }

                LuaException.L = L0;
                --LuaException.InstantiateCount;
                return(1);
            }
#endif
            else
            {
                LuaException.L = L0;
                --LuaException.InstantiateCount;
                return(LuaDLL.luaL_throw(L, "invalid arguments to method: UnityEngine.Object.Instantiate"));
            }
        }
        catch (Exception e)
        {
            LuaException.L = L0;
            --LuaException.InstantiateCount;
            return(LuaDLL.toluaL_exception(L, e));
        }
    }
 public static OpenTK.Quaternion ToOpenTK(this UnityEngine.Quaternion q)
 {
     return(new OpenTK.Quaternion(q.x, q.y, q.z, q.w));
 }
예제 #42
0
 // 線形補間
 public static UnityEngine.Quaternion linear(UnityEngine.Quaternion s, UnityEngine.Quaternion e, float t)
 {
     return(UnityEngine.Quaternion.Lerp(s, e, t));
 }
예제 #43
0
        public void ProcessPacket(CreatePrebuildsRequest packet, NebulaConnection conn)
        {
            PlanetData planet = GameMain.galaxy.PlanetById(packet.PlanetId);

            if (planet.factory == null)
            {
                Log.Warn($"planet.factory was null create new one");
                planet.factory = GameMain.data.GetOrCreateFactory(planet);
            }

            PlayerAction_Build pab = GameMain.mainPlayer.controller?.actionBuild;

            if (pab != null)
            {
                FactoryManager.TargetPlanet = packet.PlanetId;

                //Make backup of values that are overwritten
                List <BuildPreview> tmpList   = pab.buildPreviews;
                bool tmpConfirm               = pab.waitConfirm;
                UnityEngine.Vector3    tmpPos = pab.previewPose.position;
                UnityEngine.Quaternion tmpRot = pab.previewPose.rotation;

                PlanetFactory     tmpFactory       = null;
                NearColliderLogic tmpNearcdLogic   = null;
                PlanetPhysics     tmpPlanetPhysics = null;
                float             tmpBuildArea     = GameMain.mainPlayer.mecha.buildArea;
                PlanetData        tmpData          = null;
                bool loadExternalPlanetData        = GameMain.localPlanet != planet;

                //Load temporary planet data, since host is not there
                if (loadExternalPlanetData)
                {
                    tmpFactory       = (PlanetFactory)AccessTools.Field(typeof(PlayerAction_Build), "factory").GetValue(GameMain.mainPlayer.controller.actionBuild);
                    tmpNearcdLogic   = (NearColliderLogic)AccessTools.Field(typeof(PlayerAction_Build), "nearcdLogic").GetValue(GameMain.mainPlayer.controller.actionBuild);
                    tmpPlanetPhysics = (PlanetPhysics)AccessTools.Field(typeof(PlayerAction_Build), "planetPhysics").GetValue(pab);
                    tmpData          = GameMain.mainPlayer.planetData;
                }

                //Create Prebuilds from incomming packet and prepare new position
                pab.buildPreviews = packet.GetBuildPreviews();
                pab.waitConfirm   = true;
                using (FactoryManager.EventFromServer.On())
                {
                    FactoryManager.EventFactory = planet.factory;
                    pab.previewPose.position    = new UnityEngine.Vector3(packet.PosePosition.x, packet.PosePosition.y, packet.PosePosition.z);
                    pab.previewPose.rotation    = new UnityEngine.Quaternion(packet.PoseRotation.x, packet.PoseRotation.y, packet.PoseRotation.z, packet.PoseRotation.w);

                    //Check if some mandatory variables are missing
                    if (planet.physics == null || planet.physics.colChunks == null)
                    {
                        planet.physics = new PlanetPhysics(planet);
                        planet.physics.Init();
                    }
                    if (planet.aux == null)
                    {
                        planet.aux = new PlanetAuxData(planet);
                    }

                    //Set temporary Local Planet / Factory data that are needed for original methods CheckBuildConditions() and CreatePrebuilds()
                    AccessTools.Field(typeof(PlayerAction_Build), "factory").SetValue(GameMain.mainPlayer.controller.actionBuild, planet.factory);
                    AccessTools.Field(typeof(PlayerAction_Build), "planetPhysics").SetValue(GameMain.mainPlayer.controller.actionBuild, planet.physics);
                    AccessTools.Field(typeof(PlayerAction_Build), "nearcdLogic").SetValue(GameMain.mainPlayer.controller.actionBuild, planet.physics.nearColliderLogic);
                    AccessTools.Property(typeof(global::Player), "planetData").SetValue(GameMain.mainPlayer, planet, null);

                    //Check if prebuilds can be build (collision check, height check, etc)
                    GameMain.mainPlayer.mecha.buildArea = float.MaxValue;
                    bool canBuild;
                    using (FactoryManager.IgnoreBasicBuildConditionChecks.On())
                    {
                        canBuild  = pab.CheckBuildConditions();
                        canBuild &= CheckBuildingConnections(pab.buildPreviews, planet.factory.entityPool, planet.factory.prebuildPool);
                    }

                    UnityEngine.Debug.Log(pab.buildPreviews[0].condition);

                    if (canBuild)
                    {
                        FactoryManager.PacketAuthor = packet.AuthorId;
                        CheckAndFixConnections(pab, planet);
                        pab.CreatePrebuilds();
                        FactoryManager.PacketAuthor = -1;
                    }

                    //Revert changes back to the original planet
                    if (loadExternalPlanetData)
                    {
                        planet.physics.Free();
                        planet.physics = null;
                        AccessTools.Property(typeof(global::Player), "planetData").SetValue(GameMain.mainPlayer, tmpData, null);
                        AccessTools.Field(typeof(PlayerAction_Build), "planetPhysics").SetValue(GameMain.mainPlayer.controller.actionBuild, tmpPlanetPhysics);
                        AccessTools.Field(typeof(PlayerAction_Build), "factory").SetValue(GameMain.mainPlayer.controller.actionBuild, tmpFactory);
                        AccessTools.Field(typeof(PlayerAction_Build), "nearcdLogic").SetValue(GameMain.mainPlayer.controller.actionBuild, tmpNearcdLogic);
                    }

                    GameMain.mainPlayer.mecha.buildArea = tmpBuildArea;
                    FactoryManager.EventFactory         = null;
                }

                pab.buildPreviews        = tmpList;
                pab.waitConfirm          = tmpConfirm;
                pab.previewPose.position = tmpPos;
                pab.previewPose.rotation = tmpRot;

                FactoryManager.TargetPlanet = FactoryManager.PLANET_NONE;
            }
        }
예제 #44
0
        public object GetValue(CodeExecutor obj)
        {
            var v1 = value1?.GetValue(obj);
            var v2 = value2?.GetValue(obj);

            if (v1 is int i)
            {
                if (v2 is int j)
                {
                    return(i * j);
                }
                if (v2 is BigInteger bj)
                {
                    return(i * bj);
                }
                if (v2 is float f)
                {
                    return(i * f);
                }
                if (v2 is Vector3 v)
                {
                    return(i * v);
                }
                if (v2 is Vector3Int vi)
                {
                    return(i * vi);
                }
                if (v2 is string str)
                {
                    return(RepeatString(i, str));
                }
            }
            else if (v1 is float fi)
            {
                if (v2 is int j)
                {
                    return(fi * j);
                }
                if (v2 is BigInteger bj)
                {
                    return(fi * (float)bj);
                }
                if (v2 is float f)
                {
                    return(fi * f);
                }
                if (v2 is Vector3 v)
                {
                    return(fi * v);
                }
                if (v2 is Vector3Int vi)
                {
                    return(fi * (Vector3)vi);
                }
                if (v2 is string str)
                {
                    return(RepeatString(fi, str));
                }
            }
            else if (v1 is BigInteger bi)
            {
                if (v2 is int j)
                {
                    return(bi * j);
                }
                if (v2 is BigInteger bj)
                {
                    return(bi * bj);
                }
                if (v2 is float f)
                {
                    return((float)bi * f);
                }
                if (v2 is Vector3 v)
                {
                    return((float)bi * v);
                }
                if (v2 is Vector3Int vi)
                {
                    return((int)bi * vi);
                }
                if (v2 is string str)
                {
                    return(RepeatString((float)bi, str));
                }
            }
            else if (v1 is Vector3 vec1)
            {
                if (v2 is Vector3 vec2)
                {
                    return(Vector3.Dot(vec1, vec2));
                }
                if (v2 is Vector3Int vec2i)
                {
                    return(Vector3.Dot(vec1, vec2i));
                }

                if (v2 is int j)
                {
                    return(vec1 * j);
                }
                if (v2 is BigInteger bj)
                {
                    return(vec1 * (int)bj);
                }
                if (v2 is float f)
                {
                    return(vec1 * f);
                }

                if (v2 is Quaternion q2)
                {
                    return(q2 * vec1);
                }
            }
            else if (v1 is Vector3Int vec1i)
            {
                if (v2 is Vector3 vec2)
                {
                    return(Vector3.Dot(vec1i, vec2));
                }
                if (v2 is Vector3Int vec2i)
                {
                    return(vec1i.x * vec2i.x + vec1i.y * vec2i.y + vec1i.z * vec2i.z);
                }

                if (v2 is int j)
                {
                    return(vec1i * j);
                }
                if (v2 is BigInteger bj)
                {
                    return(vec1i * (int)bj);
                }
                if (v2 is float f)
                {
                    return((Vector3)vec1i * f);
                }

                if (v2 is Quaternion q2)
                {
                    return(q2 * vec1i);
                }
            }

            else if (v1 is Quaternion q)
            {
                if (v2 is Quaternion q2)
                {
                    return(Quaternion.Dot(q, q2));
                }

                if (v2 is Vector3 vec2)
                {
                    return(q * vec2);
                }
                if (v2 is Vector3Int vec2i)
                {
                    return(q * vec2i);
                }
            }

            return(0);
        }
예제 #45
0
 private void Update()
 {
     transform.rotation *=
         Quaternion.Euler((RotatingClockWise ? Vector3.up : Vector3.down) * Time.deltaTime * 20.0f);
 }
예제 #46
0
 ///
 /// This is a 2D version of Quaternion.LookAt; it returns a quaternion
 /// that makes the local +X axis point in the given forward direction.
 ///
 /// forward direction
 /// Quaternion that rotates +X to align with forward
 static Quaternion LookAt2D(Vector2 forward)
 {
     return(Quaternion.Euler(0, 0, Mathf.Atan2(forward.y, forward.x) * Mathf.Rad2Deg));
 }
예제 #47
0
 /// <summary>
 /// Find the rotation to look at a target.
 /// </summary>
 /// <param name="target">The thing to look at.</param>
 /// <returns>The needed rotation to look at the target.</returns>
 public static Quaternion GetLookAtRotation(this Transform self, Vector3 target)
 {
     return(Quaternion.LookRotation(target - self.position));
 }
예제 #48
0
    public static void PlayerCharacterPosition(int from, Vector3 position, Quaternion rotation, Quaternion childRotation, bool except)
    {
        using (Packet _packet = new Packet((int)ServerPackets.playerCharacterPosition))
        {
            _packet.Write(from);
            _packet.Write(position);
            _packet.Write(rotation);
            _packet.Write(childRotation);

            if (except)
            {
                SendTCPDataRadius(from, _packet, position, NetworkManager.visibilityRadius);
            }
            else
            {
                SendTCPDataRadius(_packet, position, NetworkManager.visibilityRadius);
            }
        }
    }
예제 #49
0
        /// <summary>Reads a Quaternion from the packet.</summary>
        /// <param name="moveReadPos">Whether or not to move the buffer's read position.</param>
        ///
        /// Reads the same as the Smallest 3 Written version
        /// Reads 3 bytes
        /// Reads the 2 fragmented bits that will indicate the index of the missing component from the 0th and 1st bytes
        /// Read the 3 smallest components
        /// Reconstruct the largest component
        public UnityEngine.Quaternion ReadQuaternion(bool moveReadPos = true)
        {
            try
            {
                byte[] components = ReadBytes(3);

                //if (largestAbsIndexBin[0])
                //    bytesToSend[0] += 128;
                //if (largestAbsIndexBin[1])
                //    bytesToSend[1] += 128;

                bool index0 = components[0] - 128 >= 0;
                bool index1 = components[1] - 128 >= 0;

                bool shouldNegateComponents = components[2] - 128 >= 0;

                if (index0)
                {
                    components[0] -= 128;
                }
                if (index1)
                {
                    components[1] -= 128;
                }

                if (shouldNegateComponents)
                {
                    components[2] -= 128;
                }

                //[00, 01, 10, 11] 00 = x, 01 = y, 10 = z, 11 = w
                //
                // Use formula x^2 + y^2 + z^2 + w^2 = 1
                // a^2 + b^2 + c^2 + r^2 = 1
                // r = sqrt(1 - a^2 - b^2 - c^2)

                float x, y, z, w;

                if (index1 && index0) //Reconstruct w
                {
                    Reconstruct(components, out x, out y, out z, out w, shouldNegateComponents);
                }
                else if (index1 && !index0) //Reconstruct z
                {
                    Reconstruct(components, out x, out y, out w, out z, shouldNegateComponents);
                }
                else if (!index1 && index0) //Reconstruct y
                {
                    Reconstruct(components, out x, out z, out w, out y, shouldNegateComponents);
                }
                else //same as -> else if (!index1 && !index1) //Reconstruct x
                {
                    Reconstruct(components, out y, out z, out w, out x, shouldNegateComponents);
                }

                UnityEngine.Quaternion value = new UnityEngine.Quaternion(x, y, z, w);

                return(value); // Return the Quaternion
            }
            catch
            {
                throw new Exception("Could not read value of type 'Quaternion'!");
            }
        }
예제 #50
0
    public void FixRoad()
    {
        foreach (var position in fixRoadCandidates)
        {
            List <Direction> neighbourDirections = PlacementHelper.FindNeighbour(position, roadDictionary.Keys);

            Quaternion rotation = Quaternion.identity;

            if (neighbourDirections.Count == 1)
            {
                Destroy(roadDictionary[position]);
                if (neighbourDirections.Contains(Direction.Down))
                {
                    rotation = Quaternion.Euler(0, 90, 0);
                }
                else if (neighbourDirections.Contains(Direction.Left))
                {
                    rotation = Quaternion.Euler(0, 180, 0);
                }
                else if (neighbourDirections.Contains(Direction.Up))
                {
                    rotation = Quaternion.Euler(0, -90, 0);
                }
                roadDictionary[position] = Instantiate(roadEnd, position, rotation, transform);
            }
            else if (neighbourDirections.Count == 2)
            {
                if (
                    neighbourDirections.Contains(Direction.Up) && neighbourDirections.Contains(Direction.Down) ||
                    neighbourDirections.Contains(Direction.Right) && neighbourDirections.Contains(Direction.Left)
                    )
                {
                    continue;
                }
                Destroy(roadDictionary[position]);
                if (neighbourDirections.Contains(Direction.Up) && neighbourDirections.Contains(Direction.Right))
                {
                    rotation = Quaternion.Euler(0, 90, 0);
                }
                else if (neighbourDirections.Contains(Direction.Right) && neighbourDirections.Contains(Direction.Down))
                {
                    rotation = Quaternion.Euler(0, 180, 0);
                }
                else if (neighbourDirections.Contains(Direction.Down) && neighbourDirections.Contains(Direction.Left))
                {
                    rotation = Quaternion.Euler(0, -90, 0);
                }
                roadDictionary[position] = Instantiate(roadCorner, position, rotation, transform);
            }
            else if (neighbourDirections.Count == 3)
            {
                Destroy(roadDictionary[position]);
                if (neighbourDirections.Contains(Direction.Right) &&
                    neighbourDirections.Contains(Direction.Down) &&
                    neighbourDirections.Contains(Direction.Left)
                    )
                {
                    rotation = Quaternion.Euler(0, 90, 0);
                }
                else if (neighbourDirections.Contains(Direction.Down) &&
                         neighbourDirections.Contains(Direction.Left) &&
                         neighbourDirections.Contains(Direction.Up))
                {
                    rotation = Quaternion.Euler(0, 180, 0);
                }
                else if (neighbourDirections.Contains(Direction.Left) &&
                         neighbourDirections.Contains(Direction.Up) &&
                         neighbourDirections.Contains(Direction.Right))
                {
                    rotation = Quaternion.Euler(0, -90, 0);
                }
                roadDictionary[position] = Instantiate(road3way, position, rotation, transform);
            }
            else
            {
                Destroy(roadDictionary[position]);
                roadDictionary[position] = Instantiate(road4way, position, rotation, transform);
            }
        }
    }
예제 #51
0
 /// <summary>
 /// Sets the transform position and rotation to the given values.
 /// </summary>
 /// <param name="position">The position to be set in the transform.</param>
 /// <param name="rotation">The rotation to be set in the transform.</param>
 public static void SetProperties(this Transform trans, Vector3 position, Quaternion rotation)
 {
     trans.position = position;
     trans.rotation = rotation;
 }
예제 #52
0
 public static DTStacks.DataType.Generic.Geometry.Quaternion Quaternion2DTStacks(this UnityEngine.Quaternion a)
 {
     DTStacks.DataType.Generic.Geometry.Quaternion b = new DTStacks.DataType.Generic.Geometry.Quaternion(a.x, a.y, a.z, a.w);
     return(b);
 }
예제 #53
0
    // Update is called once per frame
    void Update()
    {
        float delta_time = Time.deltaTime;

        // update region
        {
            _current_region = Common.ToRegion(transform.position, 0);
        }

        //if( null != _camera_controller)
        {
            // zero movement
            Vector3 movement = Vector3.zero;

            // get input
            float hinput = Input.GetAxis("Horizontal");
            float vinput = Input.GetAxis("Vertical");

            if (0 != hinput || 0 != vinput)
            {
                // get yaw
                float yaw = CameraController.Yaw;
                UnityEngine.Quaternion ryaw = UnityEngine.Quaternion.Euler(0, yaw, 0);

                // get forward and rightward
                Vector3 forward     = ryaw * Vector3.forward;
                Vector3 right       = ryaw * Vector3.right;
                Vector3 target_move = hinput * right + vinput * forward;

                // move
                {
                    movement += target_move * MaxLinearSpeed * Time.deltaTime;
                }

                // rotation
                {
                    UnityEngine.Quaternion target_dir  = UnityEngine.Quaternion.LookRotation(target_move);
                    UnityEngine.Quaternion current_dir = transform.rotation;

                    // To Angle Axis
                    float   delta_angle;
                    Vector3 delta_axis;
                    InnovaMath.ToAngleAxis(current_dir, target_dir, out delta_angle, out delta_axis);

                    float need_time = Mathf.Abs(delta_angle) / MaxAngularSpeed;

                    transform.rotation = UnityEngine.Quaternion.Slerp(transform.rotation, target_dir, Time.deltaTime / need_time);
                    _angular           = new Vector4(delta_axis.x, delta_axis.y, delta_axis.z, delta_angle > 0 ? MaxAngularSpeed : delta_angle < 0 ? -MaxAngularSpeed : 0);
                }
            }
            else
            {
                _angular = Vector4.zero;
            }

            {
                // gravity
                if (false == _character_controller.isGrounded)
                {
                    _falling += Physics.gravity * Time.deltaTime;
                    movement += _falling * Time.deltaTime;
                }
                else
                {
                    _falling = Vector3.zero;
                }

                // move
                _character_controller.Move(movement);
            }

            // let camera follow
            {
                CameraController.LookAtPosition = transform.position;
            }

            // update movement
            {
                ActorMovement new_movement = new ActorMovement();
                new_movement.Location = DataBridge.cnv(transform.localPosition);
                new_movement.Rotation = DataBridge.cnv(transform.localRotation);
                new_movement.Velocity = DataBridge.cnv(_character_controller.velocity);
                new_movement.Angular  = DataBridge.cnv(_angular);

                if (false == new_movement.Equals(_movement))
                {
                    _movement = new_movement;
                    _moved    = true;
                }
                else
                {
                    //_moved = false; // will be set false when getting.
                }
            }
        }
    }
예제 #54
0
 public override void OnPreviewAttachment(UnityEngine.Vector3 rDir, UnityEngine.Vector3 rPos, UnityEngine.Quaternion rRot)
 {
     base.OnPreviewAttachment(rDir, rPos, rRot);
 }
예제 #55
0
 /// <summary>
 /// Sets the transform rotation and scale to the given values.
 /// </summary>
 /// <param name="rotation">The rotation to be set in the transform.</param>
 /// <param name="scale">The scale to be set in the transform.</param>
 public static void SetProperties(this Transform trans, Quaternion rotation, Vector3 scale)
 {
     trans.rotation   = rotation;
     trans.localScale = scale;
 }
예제 #56
0
 /// <summary>
 /// Convert Unity Quaternion to Framework and change the coordinate system from left handed to right handed
 /// The coordinate system conversion is done by multiplying the X and W component by -1
 /// </summary>
 /// <param name="inVector">input Quaternion</param>
 /// <returns>a Framework Quaternion</returns>
 public static OmekFramework.Common.BasicTypes.SpaceTypes.Quaternion ToFramework(UnityEngine.Quaternion inQuat)
 {
     return(new OmekFramework.Common.BasicTypes.SpaceTypes.Quaternion(-inQuat.x, inQuat.y, inQuat.z, -inQuat.w));
 }
예제 #57
0
 /// <summary>
 /// Linearly interpolates between two transform.
 /// <para>When t = 0 returns a. When t = 1 returns b. When t = 0.5 returns the point midway between a and b.</para>
 /// </summary>
 public static void SetLerp(this Transform self, Transform a, Transform b, float t, bool lerpPosition = true, bool lerpRotation = true, bool lerpScale = true)
 {
     self.SetProperties(Vector3.Lerp(a.position, b.position, lerpPosition?t:0), Quaternion.Lerp(a.rotation, b.rotation, lerpRotation?t:0), Vector3.Lerp(a.localScale, b.localScale, lerpScale?t:0));
 }
예제 #58
0
 // EaseIn
 public static UnityEngine.Quaternion easeIn(UnityEngine.Quaternion s, UnityEngine.Quaternion e, float t)
 {
     return(UnityEngine.Quaternion.Lerp(s, e, Float.easeIn01(t)));
 }
예제 #59
0
 private void ChangeDirection(float direction)
 {
     _player.transform.rotation =
         Quaternion.Euler(0, direction, 0);
 }
예제 #60
0
 public static Quaternion Quaternion2Ros(Quaternion quaternion)
 {
     return(new Quaternion(-quaternion.z, quaternion.x, -quaternion.y, quaternion.w));
 }