Beispiel #1
0
    //protected override void OnFillVBO(List<UIVertex> vbo)
    protected override void OnPopulateMesh(Mesh toFill)
    {
        // requires sets of quads
        if (Points == null || Points.Length < 2)
        {
            Points = new[] { new Vector2(0, 0), new Vector2(1, 1) }
        }
        ;
        var capSize = 24;
        var sizeX   = rectTransform.rect.width;
        var sizeY   = rectTransform.rect.height;
        var offsetX = -rectTransform.pivot.x * rectTransform.rect.width;
        var offsetY = -rectTransform.pivot.y * rectTransform.rect.height;

        // don't want to scale based on the size of the rect, so this is switchable now
        if (!relativeSize)
        {
            sizeX = 1;
            sizeY = 1;
        }
        // build a new set of points taking into account the cap sizes.
        // would be cool to support corners too, but that might be a bit tough :)
        var pointList = new List <Vector2>();

        pointList.Add(Points[0]);
        var capPoint = Points[0] + (Points[1] - Points[0]).normalized * capSize;

        pointList.Add(capPoint);

        // should bail before the last point to add another cap point
        for (int i = 1; i < Points.Length - 1; i++)
        {
            pointList.Add(Points[i]);
        }
        capPoint = Points[Points.Length - 1] - (Points[Points.Length - 1] - Points[Points.Length - 2]).normalized * capSize;
        pointList.Add(capPoint);
        pointList.Add(Points[Points.Length - 1]);

        var TempPoints = pointList.ToArray();

        if (UseMargins)
        {
            sizeX   -= Margin.x;
            sizeY   -= Margin.y;
            offsetX += Margin.x / 2f;
            offsetY += Margin.y / 2f;
        }

        toFill.Clear();
        var vbo = new VertexHelper(toFill);

        Vector2 prevV1 = Vector2.zero;
        Vector2 prevV2 = Vector2.zero;

        for (int i = 1; i < TempPoints.Length; i++)
        {
            var prev = TempPoints[i - 1];
            var cur  = TempPoints[i];
            prev = new Vector2(prev.x * sizeX + offsetX, prev.y * sizeY + offsetY);
            cur  = new Vector2(cur.x * sizeX + offsetX, cur.y * sizeY + offsetY);

            float angle = Mathf.Atan2(cur.y - prev.y, cur.x - prev.x) * 180f / Mathf.PI;

            var v1 = prev + new Vector2(0, -LineThickness / 2);
            var v2 = prev + new Vector2(0, +LineThickness / 2);
            var v3 = cur + new Vector2(0, +LineThickness / 2);
            var v4 = cur + new Vector2(0, -LineThickness / 2);

            v1 = RotatePointAroundPivot(v1, prev, new Vector3(0, 0, angle));
            v2 = RotatePointAroundPivot(v2, prev, new Vector3(0, 0, angle));
            v3 = RotatePointAroundPivot(v3, cur, new Vector3(0, 0, angle));
            v4 = RotatePointAroundPivot(v4, cur, new Vector3(0, 0, angle));

            Vector2 uvTopLeft    = Vector2.zero;
            Vector2 uvBottomLeft = new Vector2(0, 1);

            Vector2 uvTopCenter    = new Vector2(0.5f, 0);
            Vector2 uvBottomCenter = new Vector2(0.5f, 1);

            Vector2 uvTopRight    = new Vector2(1, 0);
            Vector2 uvBottomRight = new Vector2(1, 1);

            Vector2[] uvs = new[] { uvTopCenter, uvBottomCenter, uvBottomCenter, uvTopCenter };

            if (i > 1)
            {
                SetVbo(vbo, new[] { prevV1, prevV2, v1, v2 }, uvs);
            }

            if (i == 1)
            {
                uvs = new[] { uvTopLeft, uvBottomLeft, uvBottomCenter, uvTopCenter }
            }
            ;
            else if (i == TempPoints.Length - 1)
            {
                uvs = new[] { uvTopCenter, uvBottomCenter, uvBottomRight, uvTopRight }
            }
            ;

            //SetVbo(vbo, new[] { v1, v2, v3, v4 }, uvs, toFill);
            vbo.AddUIVertexQuad(SetVbo(vbo, new[] { v1, v2, v3, v4 }, uvs));
            vbo.FillMesh(toFill);

            prevV1 = v3;
            prevV2 = v4;
        }
    }
Beispiel #2
0
    private void Update()
    {
        if (!reachedFullSpeed)
        {
            playerRotationInDegrees    = transform.eulerAngles.z;
            playerRotationInRadians    = playerRotationInDegrees / Mathf.Rad2Deg;
            playerRigidBody2D.velocity = new Vector2(-speed * Mathf.Sin(playerRotationInRadians), speed * Mathf.Cos(playerRotationInRadians));
        }

        if (Input.GetMouseButtonDown(0))
        {
            hingeJoint2D             = gameObject.AddComponent <HingeJoint2D>();
            playerRotationInDegrees  = transform.eulerAngles.z;
            playerRotationInRadians  = playerRotationInDegrees / Mathf.Rad2Deg;
            pivot.transform.position = Camera.main.ScreenToWorldPoint(Input.mousePosition) + new Vector3(0, 0, 10);

            pivot.GetComponent <SpriteRenderer>().enabled = true;
            hingeJoint2D.autoConfigureConnectedAnchor     = false;
            hingeJoint2D.anchor = new Vector2(0, anchorY);


            anchorPosition = transform.TransformPoint(Vector2.up * anchorY);
            hingeJoint2D.connectedAnchor = pivot.transform.InverseTransformPoint(anchorPosition);

            vectorFromPivotToPlayer = new Vector2(hingeJoint2D.connectedAnchor.x, hingeJoint2D.connectedAnchor.y);
            //Left top quadrant
            if (playerRotationInDegrees >= 0 && playerRotationInDegrees < 90)
            {
                //clockwise
                if (Vector2.Angle(vectorFromPivotToPlayer, Vector2.up) > playerRotationInDegrees && hingeJoint2D.connectedAnchor.x < 0)
                {
                    if (hingeJoint2D.connectedAnchor.y > 0)
                    {
                        jointLimit2D.max = Mathf.Atan2(hingeJoint2D.connectedAnchor.y, -hingeJoint2D.connectedAnchor.x) * Mathf.Rad2Deg;
                        jointLimit2D.min = -playerRotationInDegrees - uncertainty;
                    }
                    else
                    {
                        jointLimit2D.max = Mathf.Atan2(hingeJoint2D.connectedAnchor.y, -hingeJoint2D.connectedAnchor.x) * Mathf.Rad2Deg;
                        jointLimit2D.min = -playerRotationInDegrees - uncertainty;
                    }
                }
                //anti-clockwise
                else
                {
                    jointLimit2D.max = -Mathf.Atan2(hingeJoint2D.connectedAnchor.y, hingeJoint2D.connectedAnchor.x) * Mathf.Rad2Deg;
                    jointLimit2D.min = -playerRotationInDegrees + uncertainty;
                }
            }
            //Left bottom quadrant
            else if (playerRotationInDegrees >= 90 && playerRotationInDegrees < 180)
            {
                //anticlockwise
                if (Vector2.Angle(vectorFromPivotToPlayer, Vector2.up) < playerRotationInDegrees && hingeJoint2D.connectedAnchor.x < 0)
                {
                    jointLimit2D.max = -Mathf.Atan2(-hingeJoint2D.connectedAnchor.y, -hingeJoint2D.connectedAnchor.x) * Mathf.Rad2Deg - 180;
                    jointLimit2D.min = -playerRotationInDegrees + uncertainty;
                }
                //clockwise
                else
                {
                    jointLimit2D.max = Mathf.Atan2(-hingeJoint2D.connectedAnchor.y, hingeJoint2D.connectedAnchor.x) * Mathf.Rad2Deg - 180;
                    jointLimit2D.min = -playerRotationInDegrees - uncertainty;
                }
            }
            //Right bottom quadrant
            else if (playerRotationInDegrees >= 180 && playerRotationInDegrees < 270)
            {
                //clockwise
                if (Vector2.Angle(vectorFromPivotToPlayer, Vector2.up) < 360 - playerRotationInDegrees && hingeJoint2D.connectedAnchor.x > 0)
                {
                    jointLimit2D.max = -Mathf.Atan2(hingeJoint2D.connectedAnchor.y, hingeJoint2D.connectedAnchor.x) * Mathf.Rad2Deg + 180;
                    jointLimit2D.min = 360 - playerRotationInDegrees - uncertainty;
                }
                //anti clockwise
                else
                {
                    jointLimit2D.max = -Mathf.Atan2(-hingeJoint2D.connectedAnchor.y, -hingeJoint2D.connectedAnchor.x) * Mathf.Rad2Deg + 180;
                    jointLimit2D.min = 360 - playerRotationInDegrees + uncertainty;
                }
            }
            //Right top quadrant
            else
            {
                //anti clockwise
                if (Vector2.Angle(vectorFromPivotToPlayer, Vector2.up) > 360 - playerRotationInDegrees && hingeJoint2D.connectedAnchor.x > 0)
                {
                    if (hingeJoint2D.connectedAnchor.y > 0)
                    {
                        jointLimit2D.max = -Mathf.Atan2(hingeJoint2D.connectedAnchor.y, hingeJoint2D.connectedAnchor.x) * Mathf.Rad2Deg;
                        jointLimit2D.min = 360 - playerRotationInDegrees + uncertainty;
                    }
                    else
                    {
                        jointLimit2D.max = Mathf.Atan2(-hingeJoint2D.connectedAnchor.y, hingeJoint2D.connectedAnchor.x) * Mathf.Rad2Deg;
                        jointLimit2D.min = 360 - playerRotationInDegrees + uncertainty;
                    }
                }
                //clockwise
                else
                {
                    jointLimit2D.max = -Mathf.Atan2(hingeJoint2D.connectedAnchor.y, hingeJoint2D.connectedAnchor.x) * Mathf.Rad2Deg + 180;
                    jointLimit2D.min = 360 - playerRotationInDegrees - uncertainty;
                }
            }

            hingeJoint2D.useLimits     = true;
            hingeJoint2D.limits        = jointLimit2D;
            hingeJoint2D.connectedBody = pivot.GetChild(0).GetComponent <Rigidbody2D>();
            hingeJoint2D.enabled       = true;
            reachedFullSpeed           = false;
        }

        if (Input.GetMouseButtonUp(0))
        {
            Destroy(hingeJoint2D);
            playerRigidBody2D.freezeRotation = true;
            playerRigidBody2D.freezeRotation = false;
            reachedFullSpeed = true;
            pivotHookRigidBody2D.freezeRotation = true;
            pivotHook.rotation = Quaternion.Euler(0, 0, 0);
            pivotHookRigidBody2D.freezeRotation           = false;
            pivot.GetComponent <SpriteRenderer>().enabled = false;
            transform.Rotate(new Vector3(0, 0, -360));
        }
    }
Beispiel #3
0
 public static float Atan(Vector2 v2) => Mathf.Atan2(v2.y, v2.x);
        // Use this for initialization
        void Start()
        {
            gameObject.transform.localScale = new Vector3(imgTexture.width, imgTexture.height, 1);
            Debug.Log("Screen.width " + Screen.width + " Screen.height " + Screen.height + " Screen.orientation " + Screen.orientation);

            Mat imgMat = new Mat(imgTexture.height, imgTexture.width, CvType.CV_8UC4);

            Utils.texture2DToMat(imgTexture, imgMat);
            Debug.Log("imgMat dst ToString " + imgMat.ToString());


            float width  = imgMat.width();
            float height = imgMat.height();

            float imageSizeScale = 1.0f;
            float widthScale     = (float)Screen.width / width;
            float heightScale    = (float)Screen.height / height;

            if (widthScale < heightScale)
            {
                Camera.main.orthographicSize = (width * (float)Screen.height / (float)Screen.width) / 2;
                imageSizeScale = (float)Screen.height / (float)Screen.width;
            }
            else
            {
                Camera.main.orthographicSize = height / 2;
            }

            //set cameraparam
            int    max_d     = (int)Mathf.Max(width, height);
            double fx        = max_d;
            double fy        = max_d;
            double cx        = width / 2.0f;
            double cy        = height / 2.0f;
            Mat    camMatrix = new Mat(3, 3, CvType.CV_64FC1);

            camMatrix.put(0, 0, fx);
            camMatrix.put(0, 1, 0);
            camMatrix.put(0, 2, cx);
            camMatrix.put(1, 0, 0);
            camMatrix.put(1, 1, fy);
            camMatrix.put(1, 2, cy);
            camMatrix.put(2, 0, 0);
            camMatrix.put(2, 1, 0);
            camMatrix.put(2, 2, 1.0f);
            Debug.Log("camMatrix " + camMatrix.dump());

            MatOfDouble distCoeffs = new MatOfDouble(0, 0, 0, 0);

            Debug.Log("distCoeffs " + distCoeffs.dump());

            //calibration camera
            Size   imageSize      = new Size(width * imageSizeScale, height * imageSizeScale);
            double apertureWidth  = 0;
            double apertureHeight = 0;

            double[] fovx           = new double[1];
            double[] fovy           = new double[1];
            double[] focalLength    = new double[1];
            Point    principalPoint = new Point(0, 0);

            double[] aspectratio = new double[1];

            Calib3d.calibrationMatrixValues(camMatrix, imageSize, apertureWidth, apertureHeight, fovx, fovy, focalLength, principalPoint, aspectratio);

            Debug.Log("imageSize " + imageSize.ToString());
            Debug.Log("apertureWidth " + apertureWidth);
            Debug.Log("apertureHeight " + apertureHeight);
            Debug.Log("fovx " + fovx[0]);
            Debug.Log("fovy " + fovy[0]);
            Debug.Log("focalLength " + focalLength[0]);
            Debug.Log("principalPoint " + principalPoint.ToString());
            Debug.Log("aspectratio " + aspectratio[0]);


            //To convert the difference of the FOV value of the OpenCV and Unity.
            double fovXScale = (2.0 * Mathf.Atan((float)(imageSize.width / (2.0 * fx)))) / (Mathf.Atan2((float)cx, (float)fx) + Mathf.Atan2((float)(imageSize.width - cx), (float)fx));
            double fovYScale = (2.0 * Mathf.Atan((float)(imageSize.height / (2.0 * fy)))) / (Mathf.Atan2((float)cy, (float)fy) + Mathf.Atan2((float)(imageSize.height - cy), (float)fy));

            Debug.Log("fovXScale " + fovXScale);
            Debug.Log("fovYScale " + fovYScale);


            //Adjust Unity Camera FOV
            if (widthScale < heightScale)
            {
                ARCamera.fieldOfView = (float)(fovx[0] * fovXScale);
            }
            else
            {
                ARCamera.fieldOfView = (float)(fovy[0] * fovYScale);
            }


            MarkerDesign[] markerDesigns = new MarkerDesign[markerSettings.Length];
            for (int i = 0; i < markerDesigns.Length; i++)
            {
                markerDesigns[i] = markerSettings[i].markerDesign;
            }

            MarkerDetector markerDetector = new MarkerDetector(camMatrix, distCoeffs, markerDesigns);

            markerDetector.processFrame(imgMat, 1);


            foreach (MarkerSettings settings in markerSettings)
            {
                settings.setAllARGameObjectsDisable();
            }


            if (shouldMoveARCamera)
            {
                List <Marker> findMarkers = markerDetector.getFindMarkers();
                if (findMarkers.Count > 0)
                {
                    Marker marker = findMarkers[0];

                    if (markerSettings.Length > 0)
                    {
                        MarkerSettings settings = markerSettings[0];

                        if (marker.id == settings.getMarkerId())
                        {
                            Matrix4x4 transformationM = marker.transformation;
                            Debug.Log("transformationM " + transformationM.ToString());

                            Matrix4x4 invertZM = Matrix4x4.TRS(Vector3.zero, Quaternion.identity, new Vector3(1, 1, -1));
                            Debug.Log("invertZM " + invertZM.ToString());

                            Matrix4x4 invertYM = Matrix4x4.TRS(Vector3.zero, Quaternion.identity, new Vector3(1, -1, 1));
                            Debug.Log("invertYM " + invertYM.ToString());

                            // right-handed coordinates system (OpenCV) to left-handed one (Unity)
                            // https://stackoverflow.com/questions/30234945/change-handedness-of-a-row-major-4x4-transformation-matrix
                            Matrix4x4 ARM = invertYM * transformationM * invertYM;

                            // Apply Y-axis and Z-axis refletion matrix. (Adjust the posture of the AR object)
                            ARM = ARM * invertYM * invertZM;

                            GameObject ARGameObject = settings.getARGameObject();
                            if (ARGameObject != null)
                            {
                                ARM = ARGameObject.transform.localToWorldMatrix * ARM.inverse;

                                Debug.Log("ARM " + ARM.ToString());

                                ARGameObject.SetActive(true);
                                ARUtils.SetTransformFromMatrix(ARCamera.transform, ref ARM);
                            }
                        }
                    }
                }
            }
            else
            {
                List <Marker> findMarkers = markerDetector.getFindMarkers();
                for (int i = 0; i < findMarkers.Count; i++)
                {
                    Marker marker = findMarkers[i];

                    foreach (MarkerSettings settings in markerSettings)
                    {
                        if (marker.id == settings.getMarkerId())
                        {
                            Matrix4x4 transformationM = marker.transformation;
                            Debug.Log("transformationM " + transformationM.ToString());


                            Matrix4x4 invertYM = Matrix4x4.TRS(Vector3.zero, Quaternion.identity, new Vector3(1, -1, 1));
                            Debug.Log("invertYM " + invertYM.ToString());

                            Matrix4x4 invertZM = Matrix4x4.TRS(Vector3.zero, Quaternion.identity, new Vector3(1, 1, -1));
                            Debug.Log("invertZM " + invertZM.ToString());

                            // right-handed coordinates system (OpenCV) to left-handed one (Unity)
                            // https://stackoverflow.com/questions/30234945/change-handedness-of-a-row-major-4x4-transformation-matrix
                            Matrix4x4 ARM = invertYM * transformationM * invertYM;

                            // Apply Y-axis and Z-axis refletion matrix. (Adjust the posture of the AR object)
                            ARM = ARM * invertYM * invertZM;

                            ARM = ARCamera.transform.localToWorldMatrix * ARM;

                            Debug.Log("ARM " + ARM.ToString());

                            GameObject ARGameObject = settings.getARGameObject();
                            if (ARGameObject != null)
                            {
                                ARUtils.SetTransformFromMatrix(ARGameObject.transform, ref ARM);
                                ARGameObject.SetActive(true);
                            }
                        }
                    }
                }
            }


            Texture2D texture = new Texture2D(imgMat.cols(), imgMat.rows(), TextureFormat.RGBA32, false);

            Utils.matToTexture2D(imgMat, texture);

            gameObject.GetComponent <Renderer>().material.mainTexture = texture;
        }
Beispiel #5
0
    void Warnning(int WindowID)
    {
        GUI.DrawTexture(new Rect(left_x, left_y, num_width, num_height), left_num);
        GUI.DrawTexture(new Rect(right_x, right_y, num_width, num_height), right_num);

        if (GUI.Button(new Rect(mode_off_x / 1000f * win_rect.width, mode_off_y / 1000f * win_rect.height, mode_off_width / 1000f * win_rect.width, mode_off_height / 1000f * win_rect.height), "", Main.sty_ButtonEmpty))
        {
            //Debug.Log("sldjflkdsjflkds");

            HandWheel_OFF = true;
            X_HandWheel   = false;
            Y_HandWheel   = false;
            Z_HandWheel   = false;
//		        Axis4_HandWheel=false;
            //Debug.Log("????");

            //添加 BY:WH
            left_num = left_2;
        }
        if (GUI.Button(new Rect(mode_x_x / 1000f * win_rect.width, mode_x_y / 1000f * win_rect.height, mode_x_width / 1000f * win_rect.width, mode_x_height / 1000f * win_rect.height), "", Main.sty_ButtonEmpty))
        {
            //Debug.Log("sldjflkdsjflkds");
            HandWheel_OFF = false;
            X_HandWheel   = true;
            Y_HandWheel   = false;
            Z_HandWheel   = false;
//		        Axis4_HandWheel=false;
            MoveControl_script.x_n = true;
            //添加 BY:WH
            left_num = left_1;
        }
        if (GUI.RepeatButton(new Rect(mode_y_x / 1000f * win_rect.width, mode_y_y / 1000f * win_rect.height, mode_y_width / 1000f * win_rect.width, mode_y_height / 1000f * win_rect.height), "", Main.sty_ButtonEmpty))
        {
            //Debug.Log("sldjflkdsjflkds");
            HandWheel_OFF = false;
            X_HandWheel   = false;
            Y_HandWheel   = true;
            Z_HandWheel   = false;
//		        Axis4_HandWheel=false;
            //添加 BY:WH
            left_num = mid;

            //Main.MoveControl_script.speed_to_move = 0.16667F;//内容--JOG模式下,慢常速为10m/min=(10/60)m/s,因此spee-to-move=10/60,姓名--刘旋,时间--2013-4-8
            //Main.MoveControl_script.move_rate = 1f;
            //Main.MoveControl_script.y_n=true;
            //MoveControl_script.audio.Play();

            //MoveControl_script.audio.Stop();
        }
        if (GUI.Button(new Rect(mode_z_x / 1000f * win_rect.width, mode_z_y / 1000f * win_rect.height, mode_z_width / 1000f * win_rect.width, mode_z_height / 1000f * win_rect.height), "", Main.sty_ButtonEmpty))
        {
            //Debug.Log("sldjflkdsjflkds");
            HandWheel_OFF = false;
            X_HandWheel   = false;
            Y_HandWheel   = false;
            Z_HandWheel   = true;
//		        Axis4_HandWheel=false;
            //添加 BY:WH
            left_num = right_1;
        }
        if (GUI.Button(new Rect(mode_4_x / 1000f * win_rect.width, mode_4_y / 1000f * win_rect.height, mode_4_width / 1000f * win_rect.width, mode_4_height / 1000f * win_rect.height), "", Main.sty_ButtonEmpty))
        {
            //Debug.Log("sldjflkdsjflkds");
            HandWheel_OFF = false;
            X_HandWheel   = false;
            Y_HandWheel   = false;
            Z_HandWheel   = false;
//		        Axis4_HandWheel=true;
            //添加 BY:WH
            left_num = right_2;
        }

        if (GUI.Button(new Rect(mode_1_x / 1000f * win_rect.width, mode_1_y / 1000f * win_rect.height, mode_1_width / 1000f * win_rect.width, mode_1_height / 1000f * win_rect.height), "", Main.sty_ButtonEmpty))
        {
            //Debug.Log("sldjflkdsjflkds");
            Scale_Offset_HandWheel = 0.000001f;
            //添加 BY:WH
            right_num = left_1;
        }
        if (GUI.Button(new Rect(mode_10_x / 1000f * win_rect.width, mode_10_y / 1000f * win_rect.height, mode_10_width / 1000f * win_rect.width, mode_10_height / 1000f * win_rect.height), "", Main.sty_ButtonEmpty))
        {
            //Debug.Log("sldjflkdsjflkds");
            Scale_Offset_HandWheel = 0.00001f;
            //添加 BY:WH
            right_num = mid;
        }
        if (GUI.Button(new Rect(mode_100_x / 1000f * win_rect.width, mode_100_y / 1000f * win_rect.height, mode_100_width / 1000f * win_rect.width, mode_100_height / 1000f * win_rect.height), "", Main.sty_ButtonEmpty))
        {
            //Debug.Log("sldjflkdsjflkds");
            Scale_Offset_HandWheel = 0.0001f;
            //添加 BY:WH
            right_num = right_1;
        }
//			if (GUI.Button(new Rect(350f/1000f*win_rect.width,20f/1000f*win_rect.height, 120f/1000f*win_rect.width, 70f/1000f*win_rect.height), "+1格"))
//				//手轮往右移动一格
//			{
//				//Debug.Log("sldjflkdsjflkds");
//				handWheelDirection=1;
//				axlePostionChange();
//			}
//			if (GUI.Button(new Rect(350f/1000f*win_rect.width,220f/1000f*win_rect.height, 120f/1000f*win_rect.width, 70f/1000f*win_rect.height), "-1格"))
//			{
//				//Debug.Log("sldjflkdsjflkds");
//				handWheelDirection=2;
//				axlePostionChange();
//			}



        if (!handWheelActive)
        {
            GUIUtility.RotateAroundPivot(rotatedAngle, handWheelOrigin);
            GUI.DrawTexture(handWheelPlaneRect, plane);
        }

        if (handWheelActive)
        {
            //Debug.Log("active");
            //获取当前鼠标坐标
            Vector3 currentMousePos = Input.mousePosition;
            //handWheelAreaRect=new Rect(currentMousePos.x-size,Screen.height-currentMousePos.y-size,2*size,2*size);
            //计算在手轮圆心的哪一侧
            currentMousePos.y = Screen.height - currentMousePos.y;
            //根据相对手轮圆心的位置和鼠标y值的变化趋势确定是+1格还是-1格
            currentMousePos.x -= win_rect.x;
            currentMousePos.y -= win_rect.y;
            //Debug.Log("????"+currentMousePos.x+"???"+currentMousePos.y);
            //Debug.Log("ooo"+lastMousePos.x+"ooo"+lastMousePos.y);
            //Debug.Log("cuu"+currentMousePos.y+" last:"+lastMousePos.y);

            if (currentMousePos.x > handWheelOrigin.x && currentMousePos.y < lastMousePos.y)
            {
                handWheelDirection = 2;              //-1格;
            }
            else if (currentMousePos.x > handWheelOrigin.x && currentMousePos.y > lastMousePos.y)
            {
                handWheelDirection = 1;              //+1格
            }
            else if (currentMousePos.x < handWheelOrigin.x && currentMousePos.y < lastMousePos.y)
            {
                handWheelDirection = 1;
            }
            else if (currentMousePos.x < handWheelOrigin.x && currentMousePos.y > lastMousePos.y)
            {
                handWheelDirection = 2;
            }
            //根据tan值求angle

            float rotateAngle = 180 - Mathf.Atan2(currentMousePos.x - handWheelOrigin.x, currentMousePos.y - handWheelOrigin.y) * Mathf.Rad2Deg;
            //Debug.Log("ra:"+rotateAngle);
            //handWheelAreaRect=new Rect((handWheelRadius)*(Mathf.Sin(rotateAngle/Mathf.Rad2Deg))+handWheelOrigin.x-size,(-Mathf.Cos(rotateAngle/Mathf.Rad2Deg))*handWheelRadius+handWheelOrigin.y-size,2*size,2*size);
            //旋转贴图

            //若angle>=阈值,响应的X_offset_handWheel或Y_offset_handWheel或z_offset_handWheel改变
            //Debug.Log(handWheelAreaRect);
            float r = Mathf.Abs((Mathf.Abs(rotateAngle) - Mathf.Abs(currRotateAngle)));
            //Debug.Log(Mathf.Abs(rotateAngle)+"  "+Mathf.Abs(currRotateAngle));
            //Debug.Log(rotateAngle+"PPPP"+currRotateAngle);
            //Debug.Log(handWheelDirection+"QQQ");
            //Debug.Log(r);
            if (r >= deltaAngle)
            {
                //Debug.Log("rotateangle");
                //Debug.Log(rotateAngle);
                //Debug.Log("currRotateAngle");
                //Debug.Log(currRotateAngle);
                //根据handwheeldirection旋转rotateangle度
                float thedeltAngle = rotateAngle - angleOffset;
                //Debug.Log(thedeltAngle+rotatedAngle+"QQ");
                if ((thedeltAngle + rotatedAngle) != 0)
                {
                    audio.Play();
                }
                if (thedeltAngle >= 0)
                {
                    GUIUtility.RotateAroundPivot(thedeltAngle + rotatedAngle, handWheelOrigin);
                    //sumAngle+=thedeltAngle;
                }

                else
                {
                    GUIUtility.RotateAroundPivot(360 + thedeltAngle + rotatedAngle, handWheelOrigin);
                    // sumAngle+=(360+thedeltAngle);
                }
                //Debug.Log("dfds");
                GUI.DrawTexture(handWheelPlaneRect, plane);
                //handWheelAreaRect=new Rect(currentMousePos.x -size,currentMousePos.y-size,2*size,2*size);
                lastMousePos = currentMousePos;
                //if(Mathf.Abs((Mathf.Abs(rotateAngle)-Mathf.Abs(currRotateAngle)))>=deltaAngle)
                //{

                /*
                 * if(handWheelDirection==1)
                 * {
                 *
                 *      //handWheelPoint.x=
                 *      //ChangeHandWheelPoint();
                 *
                 *      if(X_HandWheel)
                 *      {
                 *              X_Offset_HandWheelSet+=Scale_Offset_HandWheel;
                 *              Debug.Log("x+1");
                 *      }
                 *      else if(Y_HandWheel)
                 *              Y_Offset_HandWheelSet+=Scale_Offset_HandWheel;
                 *      else if(Z_HandWheel)
                 *              Z_Offset_HandWheelSet+=Scale_Offset_HandWheel;
                 * }
                 * else if(handWheelDirection==2)
                 * {
                 *      if(X_HandWheel)
                 *      {
                 *              X_Offset_HandWheelSet-=Scale_Offset_HandWheel;
                 *              Debug.Log("x-1");
                 *      }
                 *      else if(Y_HandWheel)
                 *              Y_Offset_HandWheelSet-=Scale_Offset_HandWheel;
                 *      else if(Z_HandWheel)
                 *              Z_Offset_HandWheelSet-=Scale_Offset_HandWheel;
                 * }
                 */
                //}
                currRotateAngle = rotateAngle;
                axlePostionChange();
            }
            else
            {
                float thedeltAngle = currRotateAngle - angleOffset;
                if (thedeltAngle >= 0)
                {
                    GUIUtility.RotateAroundPivot(thedeltAngle + rotatedAngle, handWheelOrigin);
                }
                else
                {
                    GUIUtility.RotateAroundPivot(360 + thedeltAngle + rotatedAngle, handWheelOrigin);
                }
                GUI.DrawTexture(handWheelPlaneRect, plane);
            }
        }
        //添加 BY:WH
        //GUI.Button(new Rect(handWheelOrigin_x-70,handWheelOrigin_y-70,140,140),"圆心");

        /*
         * Vector3 mousePos=Input.mousePosition;
         * mousePos.x-=(win_rect.x);
         * mousePos.y=Screen.height-mousePos.y;
         * mousePos.y-=(win_rect.y);
         * if(!handWheelAreaRect.Contains(mousePos))
         * {
         *      GUI.DragWindow();
         *
         * }
         */

        GUI.DragWindow();

        //Debug.Log("bbb");
    }
Beispiel #6
0
        protected override void OnFixedUpdate()
        {
            base.OnFixedUpdate();
            if (!HighLogic.LoadedSceneIsFlight)
            {
                return;
            }
            if (!enableTracking)
            {
                return;
            }

            //Update GUI
            Fields["trackRandomObjects"].guiActive = !targetObjectSet && canTrackRandomObjects;
            Events["ClearTarget"].active           = trackRandomObjects && !targetObjectSet && canTrackRandomObjects;

            /*
             * //Check to see if we've moved into the rotation threshold.
             * if (Mathf.Abs(targetAngle) <= kAcquisitionRotationThresholdAngle)
             * {
             *  trackingStatus = targetName;
             *  losCooldownStart = Planetarium.GetUniversalTime();
             *
             *  //If we will only track for a limited time, then check our expiration timer
             *  if (randomTrackDuration > 0)
             *  {
             *      if (randomTrackStart == -1f)
             *      {
             *          randomTrackStart = Planetarium.GetUniversalTime();
             *      }
             *      else if (Planetarium.GetUniversalTime() - randomTrackStart >= randomTrackDuration)
             *      {
             *          targetTransform = null;
             *          randomTrackStart = -1f;
             *      }
             *  }
             * }
             */

            //If the servo is moving then wait until it's done.
            if (IsMoving())
            {
                return;
            }

            //Update the tracking target
            bool hasTargetToTrack = UpdateTarget();

            //If we have no target to track then we're done.
            if (!hasTargetToTrack)
            {
                return;
            }

            //Calculate and set target rotation
            Vector3 inversePosition;

            if (rotationTransform != null && rotationReferenceTransform != null)
            {
                inversePosition     = rotationTransform.InverseTransformPoint(targetTransform.position);
                targetRotationAngle = Mathf.Atan2(inversePosition.y, inversePosition.z) * Mathf.Rad2Deg;

                //Set the target angle
                Fields["targetAngle"].SetValue(targetRotationAngle, this);
            }
        }
Beispiel #7
0
    private void Update()
    {
        if (GameManager.Instance.gamePaused)
        {
            return;
        }

        if (light > 0)
        {
            gameObject.tag = "Player";

            if (!trail.activeSelf)
            {
                trail.SetActive(true);
            }

            GetComponent <Light>().color = original_color;
        }

        if (light <= 0)
        {
            gameObject.tag = "Dead";
        }

        if (gameObject.tag == "Dead")
        {
            GetComponent <Light>().color = new Color(19f / 255f, 19f / 255f, 19f / 255f, 122f / 255f);
            if (trail.activeSelf)
            {
                trail.SetActive(false);
            }
        }

        switch (playerNumber)
        {
        case 1:
            Player1Control();
            break;

        case 2:
            Player2Control();
            break;
        }

        if (m_Vertical == 0 && m_Horizontal == 0)
        {
            m_Rigidbody.velocity = new Vector2(0, 0);
        }
        else if (!boosting)
        {
            m_Angle = Mathf.Atan2(m_Vertical, m_Horizontal);
            transform.eulerAngles = new Vector3(0, 0, m_Angle * Mathf.Rad2Deg);
            force.x = Mathf.Cos(m_Angle);
            force.y = Mathf.Sin(m_Angle);
            force.x = force.x * speed;
            force.y = force.y * speed;
            m_Rigidbody.velocity = new Vector2(force.x, force.y) * speed;
        }

        if (currentBoostTime < boostTime)
        {
            Debug.Log("BOOSTING");
            ApplyBoostForce();
            currentBoostTime += Time.deltaTime;
        }
        else
        {
            boostAcceleration = speed;
            boosting          = false;
        }
    }
Beispiel #8
0
    //사진에서 값 처리
    void Update()
    {
        tex2 = MakeTexture2D(carm.targetTexture);

        Mat imgMat = new Mat(tex2.height, tex2.width, CvType.CV_8UC3);

        Utils.texture2DToMat(tex2, imgMat);

        //GrayScale 생성
        Mat grayMat = new Mat();

        Imgproc.cvtColor(imgMat, grayMat, Imgproc.COLOR_RGB2GRAY);

        //Canny적용
        Mat cannyMat = new Mat();

        Imgproc.Canny(grayMat, cannyMat, 70, 200);

        //ROI 설정
        grayMat.locateROI(new Size(200, 100), new Point(60, 60));

        //HoughLine생성
        Mat lines = new Mat();

        Imgproc.HoughLinesP(cannyMat, lines, 1, Mathf.PI / 180, 30, 40, 40);

        int[] linesArray = new int[lines.cols() * lines.rows() * lines.channels()];

        lines.get(0, 0, linesArray);


        line_count    = 0;
        is_Left_Line  = false;
        is_Right_Line = false;
        right_point.Initialize();
        left_point.Initialize();

        for (int i = 0; i < linesArray.Length; i = i + 4)
        {
            //   Debug.Log(Mathf.Atan2((linesArray[i + 2] - linesArray[i + 0]), (linesArray[i + 3] - linesArray[i + 1])) * Mathf.Rad2Deg);
            if (line_count >= 2)
            {
                break;
            }

            if (!is_Left_Line)
            {
                //각제한
                if (5 < Mathf.Atan2((linesArray[i + 2] - linesArray[i + 0]), (linesArray[i + 3] - linesArray[i + 1])) * Mathf.Rad2Deg)
                {
                    if (80 > Mathf.Atan2((linesArray[i + 2] - linesArray[i + 0]), (linesArray[i + 3] - linesArray[i + 1])) * Mathf.Rad2Deg)
                    {
                        Imgproc.line(imgMat, new Point(linesArray[i + 0], linesArray[i + 1]), new Point(linesArray[i + 2], linesArray[i + 3]), new Scalar(255, 0, 0), 4);
                        line_count++;
                        is_Left_Line = true;
                        for (int j = 0; j < left_point.Length; j++)
                        {
                            left_point[j] = linesArray[i + j];
                        }
                    }
                }
            }

            if (!is_Right_Line)
            {
                //각제한
                if (120 < Mathf.Atan2((linesArray[i + 2] - linesArray[i + 0]), (linesArray[i + 3] - linesArray[i + 1])) * Mathf.Rad2Deg)
                {
                    if (175 > Mathf.Atan2((linesArray[i + 2] - linesArray[i + 0]), (linesArray[i + 3] - linesArray[i + 1])) * Mathf.Rad2Deg)
                    {
                        Imgproc.line(imgMat, new Point(linesArray[i + 0], linesArray[i + 1]), new Point(linesArray[i + 2], linesArray[i + 3]), new Scalar(255, 0, 0), 4);
                        line_count++;
                        is_Right_Line = true;
                        for (int j = 0; j < right_point.Length; j++)
                        {
                            right_point[j] = linesArray[i + j];
                        }
                    }
                }
            }
        }

        int[] van = Find_Vanishing_Point(left_point, right_point);

        Texture2D texture  = new Texture2D(imgMat.cols(), imgMat.rows(), TextureFormat.RGBA32, false);
        Texture2D texture2 = new Texture2D(grayMat.cols(), grayMat.rows(), TextureFormat.RGBA32, false);

        Utils.matToTexture2D(imgMat, texture);
        Utils.matToTexture2D(cannyMat, texture2);

        GameObject.FindGameObjectWithTag("test").GetComponent <Renderer>().material.mainTexture = texture;
        //GameObject.Find("test2").GetComponent<Renderer>().material.mainTexture = texture2;

        //자동차에 값 전달
        Vector2 diretion = Get_Vector(van, imgMat);

        car_AI.Change_Value_Steering(diretion);

        //Debug.Log("van point : "+diretion.x +" : " + diretion.y);
    }
    // Use this for initialization
    IEnumerator Start()
    {
        PersistentStorage.init();
        ReadImagetargetPosition.init();
        list = PersistentStorage.findForImageTargetId(gameObject.name);
        currentImagetargetInfo = ReadImagetargetPosition.findForImageTargetPosition(gameObject.name);
        allImagetargetInfo     = ReadImagetargetPosition.getAllImagetargerPositionInfo();
        foreach (Row row in list)
        {
            Vector3 shrinkedPos = new Vector3(row.localPosition.x / 3.0f,
                                              row.localPosition.y / 3.0f,
                                              row.localPosition.z / 3.0f);
            Vector3    position    = transform.TransformPoint(shrinkedPos);
            Quaternion rotation    = transform.rotation * row.localRotation;
            GameObject videoPlayer = Instantiate(videoPlayerPrefab, transform);
            videoPlayerList.Add(videoPlayer);
            videoPlayer.transform.position = position;
            videoPlayer.transform.rotation = rotation;
            GameObject videoPlane = videoPlayer.transform.Find("VideoPlane").gameObject;
            TextMesh   videoName  = videoPlayer.transform.Find("VideoName").GetComponent <TextMesh>();
            videoName.text = row.videoPath;
            VideoPlayer player = videoPlane.GetComponent <VideoPlayer>();
            player.url = Application.persistentDataPath + "/" + row.videoPath;
            Debug.LogFormat("Row: {0} {1}", row.imageTargetId, row.videoPath);
            player.Play();
            timelineController.rowVideoList.Add(new RowVideoPair(row, videoPlayer));
        }

        foreach (ImagetargetPositionInfo info in allImagetargetInfo)
        {
            if (info.imageTargetId == this.gameObject.name)
            {
                initPos = new Vector3(info.x, info.y, info.z);
                arrows.Add(null);
                arrowsToOriginDistance.Add(0.0f);
                Debug.LogFormat("Image Target: {0} Pos: {1}", info.imageTargetId, initPos);
            }
            else
            {
                GameObject newArrow     = GameObject.Instantiate(arrowPrefab, transform);
                TextMesh   pointedImage = newArrow.transform.Find("pointedImage").GetComponent <TextMesh>();
                pointedImage.text = info.imageTargetId;
                float distance = Vector3.Distance(transform.position, newArrow.transform.position);
                arrows.Add(newArrow);
                arrowsToOriginDistance.Add(distance);
            }
        }
        Vector3 curPos = transform.position;

        for (int i = 0; i < allImagetargetInfo.Count; i++)
        {
            if (arrows [i] != null)
            {
                float radians = Mathf.Atan2(initPos.z - allImagetargetInfo[i].z, initPos.x - allImagetargetInfo[i].x);
                arrows[i].transform.eulerAngles = new Vector3(0, radians * 180 / Mathf.PI, 0);
                arrows[i].transform.position    = new Vector3(curPos.x - arrowsToOriginDistance[i] * Mathf.Cos(radians),
                                                              arrows[i].transform.position.y,
                                                              curPos.z - arrowsToOriginDistance[i] * Mathf.Sin(radians));
            }
        }
        yield return(new WaitForSeconds(1f));        //wait the first frame to show up

        foreach (GameObject videoPlayer in videoPlayerList)
        {
            GameObject  videoPlane = videoPlayer.transform.Find("VideoPlane").gameObject;
            VideoPlayer player     = videoPlane.GetComponent <VideoPlayer>();
            player.Pause();
            int videoWidth  = player.texture.width;
            int videoHeight = player.texture.height;
            Debug.LogFormat("Video width: {0} height: {1}", videoWidth, videoHeight);
            videoPlane.transform.localScale = new Vector3(videoPlane.transform.localScale.x,
                                                          videoPlane.transform.localScale.y,
                                                          videoPlane.transform.localScale.z * videoHeight / videoWidth);
        }
    }
        private void UpdateHandles(Foliage2D_Path path2D, GUIStyle iconStyle)
        {
            Quaternion inv = Quaternion.Inverse(path2D.transform.rotation);

            Handles.color = new Color(1, 1, 1, 0);
            Vector3 global, tGlobal = Vector3.zero;

            handleSelected = false;

            for (int i = 0; i < path2D.handlesPosition.Count; i++)
            {
                // global position of a path point
                Vector3 pos        = path2D.transform.position + Vector3.Scale(new Vector3(path2D.handlesPosition[i].x, path2D.handlesPosition[i].y, 0), path2D.transform.localScale);
                Vector3 tPos       = path2D.transform.position + Vector3.Scale(new Vector3(path2D.handleControlsPos[i].x, path2D.handleControlsPos[i].y, 0), path2D.transform.localScale);
                bool    isSelected = selectedPoints.Contains(i);

                if (!handleSelected)
                {
                    handleSelected = selectedPoints.Contains(i);
                }

                Texture2D tex = null;
                tex = isSelected ? texDotSelected : texDot;

                if (IsVisible(pos))
                {
                    SetScale(pos, tex, ref iconStyle);
                    Handles.Label(pos, new GUIContent(tex), iconStyle);
                }

                if (!path2D.uniformValues && path2D.foliagePathType == Foliage2D_PathType.Smooth && IsVisible(tPos) && selectedPoints.Contains(i))
                {
                    SetScale(tPos, texBlueDot, ref iconStyle);
                    Handles.Label(tPos, new GUIContent(texBlueDot), iconStyle);
                }

                global = Handles.FreeMoveHandle(pos, Quaternion.identity, HandleScale(pos), Vector3.zero, Handles.CircleHandleCap);

                if (!path2D.uniformValues && path2D.foliagePathType == Foliage2D_PathType.Smooth)
                {
                    tGlobal = Handles.FreeMoveHandle(tPos, Quaternion.identity, HandleScale(tPos), Vector3.zero, Handles.CircleHandleCap);
                }

                if (global != pos)
                {
                    selectedPoints.Clear();
                    selectedPoints.Add(i);
                    isSelected = true;

                    Vector3 local = inv * (global - path2D.transform.position);

                    Vector2 relative = new Vector2(
                        local.x / path2D.transform.localScale.x,
                        local.y / path2D.transform.localScale.y) - path2D.handlesPosition[i];

                    path2D.handlesPosition[selectedPoints[0]]   += relative;
                    path2D.handleControlsPos[selectedPoints[0]] += relative;

                    index = i;
                }

                if (tGlobal != tPos && !path2D.uniformValues && path2D.foliagePathType == Foliage2D_PathType.Smooth)
                {
                    Vector3 local = inv * (tGlobal - path2D.transform.position);

                    Vector2 relative = new Vector2(
                        local.x / path2D.transform.localScale.x,
                        local.y / path2D.transform.localScale.y) - path2D.handleControlsPos[i];

                    path2D.handleControlsPos[selectedPoints[0]] += relative;
                    path2D.nodeTension[i] = -Vector2.Distance(path2D.handleControlsPos[i], path2D.handlesPosition[i]) + 2f;

                    Vector2 line       = path2D.handleControlsPos[i] - path2D.handlesPosition[i];
                    float   angleInDeg = Mathf.Atan2(line.y, line.x) * Mathf.Rad2Deg;

                    if (angleInDeg > 0)
                    {
                        path2D.nodeBias[i] = -4 * angleInDeg / 180f;
                    }
                    else
                    {
                        path2D.nodeBias[i] = -4 * angleInDeg / 180f;
                    }
                }

                // make sure we can add new point at the midpoints!
                if (i + 1 < path2D.handlesPosition.Count)
                {
                    int     index       = i + 1;
                    Vector3 pos2        = path2D.transform.position + path2D.transform.rotation * Vector3.Scale(new Vector3(path2D.handlesPosition[index].x, path2D.handlesPosition[index].y, 0), path2D.transform.localScale);
                    Vector3 mid         = (pos + pos2) / 2;
                    float   handleScale = HandleScale(mid);

                    if (Handles.Button(mid, SceneView.lastActiveSceneView.camera.transform.rotation, handleScale, handleScale, Handles.CircleHandleCap))
                    {
                        Vector2 pt = inv * new Vector2((mid.x - path2D.transform.position.x) / path2D.transform.localScale.x, (mid.y - path2D.transform.position.y) / path2D.transform.localScale.y);

                        path2D.handlesPosition.Insert(index, pt);
                        path2D.handleControlsPos.Insert(index, new Vector2(pt.x + 2f, pt.y));
                        path2D.nodeTension.Insert(index, 0f);
                        path2D.nodeBias.Insert(index, 0f);
                    }
                    if (IsVisible(mid))
                    {
                        SetScale(mid, texDotPlus, ref iconStyle);
                        Handles.Label(mid, new GUIContent(texDotPlus), iconStyle);
                    }
                }

                // check if we want to remove points
                if (Event.current.alt && path2D.handlesPosition.Count > 2)
                {
                    float handleScale = HandleScale(pos);
                    if (IsVisible(pos))
                    {
                        SetScale(pos, texMinus, ref iconStyle);
                        Handles.Label(pos, new GUIContent(texMinus), iconStyle);
                    }

                    if (Handles.Button(pos, SceneView.lastActiveSceneView.camera.transform.rotation, handleScale, handleScale, Handles.CircleHandleCap))
                    {
                        if (!isSelected)
                        {
                            selectedPoints.Clear();
                            selectedPoints.Add(i);
                        }
                        for (int s = 0; s < selectedPoints.Count; s++)
                        {
                            path2D.handlesPosition.RemoveAt(selectedPoints[s]);
                            path2D.handleControlsPos.RemoveAt(selectedPoints[s]);
                            path2D.nodeTension.RemoveAt(selectedPoints[s]);
                            path2D.nodeBias.RemoveAt(selectedPoints[s]);

                            if (selectedPoints[s] <= i)
                            {
                                i--;
                            }

                            for (int u = 0; u < selectedPoints.Count; u++)
                            {
                                if (selectedPoints[u] > selectedPoints[s])
                                {
                                    selectedPoints[u] -= 1;
                                }
                            }
                        }
                        selectedPoints.Clear();
                        GUI.changed = true;
                    }
                }
            }
        }
Beispiel #11
0
 private void FixedUpdate()
 {
     body.SetRotation(Mathf.Atan2(movement.vector.x, -movement.vector.y) * Mathf.Rad2Deg);
     body.velocity       = movement.vector * playerData.speed;
     playerData.position = this.transform.position;
 }
Beispiel #12
0
    void Update()
    {
        var aimAngle = Mathf.Atan2(Input.GetAxis("Vertical2"), Input.GetAxis("Horizontal2"));

        if (aimAngle < 0f)
        {
            aimAngle = Mathf.PI * 2 + aimAngle;
        }
        if (aimAngle == 0f)
        {
            crosshair.gameObject.SetActive(false);
        }
        else
        {
            crosshair.gameObject.SetActive(true);
        }
        var aimDirection = Quaternion.Euler(0, 0, aimAngle * Mathf.Rad2Deg) * Vector2.right;

        playerPosition = transform.position;
        if (!ropeAttached)
        {
            SetCrosshairPosition(aimAngle);
            playerMovement.isSwinging = false;
        }
        else
        {
            playerMovement.isSwinging = true;
            playerMovement.ropeHook   = ropePositions.Last();
            crosshairSprite.enabled   = false;

            // Wrap rope around points of colliders if there are raycast collisions between player position and their closest current wrap around collider / angle point.
            if (ropePositions.Count > 0)
            {
                Debug.Log(ropePositions.Count);
                Vector2 lastRopePoint = ropePositions.Last();

                RaycastHit2D playerToCurrentNextHit = Physics2D.Raycast(playerPosition, (lastRopePoint - playerPosition).normalized, Vector2.Distance(playerPosition, lastRopePoint) - 0.1f, ropeLayerMask);
                if (playerToCurrentNextHit)
                {
                    var colliderWithVertices = playerToCurrentNextHit.collider as PolygonCollider2D;
                    if (colliderWithVertices != null)
                    {
                        var closestPointToHit = GetClosestColliderPointFromRaycastHit(playerToCurrentNextHit, colliderWithVertices);
                        if (wrapPointsLookup.ContainsKey(closestPointToHit))
                        {
                            // Reset the rope if it wraps around an 'already wrapped' position.
                            ResetRope();
                            return;
                        }

                        ropePositions.Add(closestPointToHit);
                        wrapPointsLookup.Add(closestPointToHit, 0);
                        distanceSet = false;
                    }
                }
            }
        }

        UpdateRopePositions();
        HandleRopeLength();
        HandleInput(aimDirection);
        HandleRopeUnwrap();
        Vector3 dir = (this.transform.position - crosshair.transform.position);

        Debug.DrawLine(playerPosition, crosshair.position - dir * 10, Color.red);
    }
    void InputControllerNoneFlyingNoneTwinStick()
    {
        //Check if player is grounded
        RaycastHit2D hit = Physics2D.Raycast(transform.position, Vector2.down);

        if (hit.transform != null)
        {
            if (hit.transform.tag == "Ground")
            {
                currentGroundDist = Mathf.Abs(hit.point.y - transform.position.y);
                if (currentGroundDist < normalGroundDist && rB.velocity.y <= 0)
                {
                    grounded   = true;
                    doubleJump = true;
                }
            }
        }
        if (!useKeyboard) //Use XBox controller input
        {
            vert  = -iC.LeftVertical();
            horiz = iC.LeftHorizontal();
            if (vert != 0 || horiz != 0)
            {
                droneArm.transform.eulerAngles = new Vector3(
                    droneArm.transform.eulerAngles.x,
                    droneArm.transform.eulerAngles.y,
                    turnAmount - 90.0f
                    );
            }
            if (vert > -0.5f && vert < 0.05f)
            {
                vert = 0;
                if (horiz > 0)
                {
                    horiz = 1;
                }
                else if (horiz < 0)
                {
                    horiz = -1;
                }
            }
            else
            {
                horiz = 0f;
                if (vert <= -0.5f)
                {
                    vert = -1f;
                }
                else if (vert >= 0.5f)
                {
                    vert = 1f;
                }
            }
            turnAmount = (Mathf.Atan2(horiz, vert) * Mathf.Rad2Deg);
            if (horiz < 0)
            {
                GetComponent <SpriteRenderer>().flipX = true;
            }
            else if (horiz > 0)
            {
                GetComponent <SpriteRenderer>().flipX = false;
            }
            if (iC.RightTrigger() > 0 && canFire)
            {
                canFire = false;
                StartCoroutine(HoldingRightTrigger());
            }
            if (iC.PressedA() && grounded)
            {
                grounded = false;
                rB.AddForce(new Vector2(0, jumpStrength), ForceMode2D.Impulse);
            }
        }
        else // the player is using a keyboard, lets follow the mouse instead
        {
            var objectPos = Camera.main.WorldToScreenPoint(droneArm.transform.position);
            var dir       = Input.mousePosition - objectPos;
            droneArm.transform.rotation = Quaternion.Euler(new Vector3(0, 0, Mathf.Atan2(dir.y, dir.x) * Mathf.Rad2Deg));

            //Attack input detection
            if (Input.GetButton("Fire1") && canFire)
            {
                canFire = false;
                StartCoroutine(HoldingRightTrigger());
            }

            //Flip drone sprite to face direction of arm
            if (dir.x < 0)
            {
                GetComponent <SpriteRenderer>().flipX = true;
            }
            else if (dir.x > 0)
            {
                GetComponent <SpriteRenderer>().flipX = false;
            }
            if (Input.GetKeyDown(KeyCode.Space) && grounded)
            {
                grounded = false;
                rB.AddForce(new Vector2(0, jumpStrength), ForceMode2D.Impulse);
            }
        }
    }
Beispiel #14
0
 /// <summary>
 /// Returns the specific rotation from a particular direction vector
 /// </summary>
 /// <param name = "transform"> The specific component transform</param>
 public static Quaternion CalculateRotation2D(Vector2 direction)
 {
     return(Quaternion.AngleAxis(Mathf.Atan2(direction.y, direction.x) * Mathf.Rad2Deg, Vector3.forward));
 }
        public void Update(float delta)
        {
            delta *= 1f;
            if (directionalKeysWhereActiveThePreviousFrame == false)
            {
                if (directionalKeys.IsActive())
                {
                    directionalKeysWhereActiveThePreviousFrame = true;
                    angleFromDirectionalKeys = angleGoal = previousAngle = directionalKeys.AngleFromKey();
                    angleDistance            = 0;
                    timeInAngleGoal          = 0;
                    _joystick.Angle          = lastAngle;
                    _joystick.Distance       = ControllerSettings.JOYSTICK_EMULATOR_MINIUM_DISTANCE_ANGLE_ANIMATION;
                    return;
                }
                else
                {
                    return;
                }
            }

            if (directionalKeys.IsActive())
            {
                // wasActive = true;
                angleFromDirectionalKeys = directionalKeys.AngleFromKey();

                if (angleFromDirectionalKeys != angleGoal)
                {
                    previousAngle   = NormalizeAngle(lastAngle);
                    angleGoal       = angleFromDirectionalKeys;
                    angleDistance   = angleGoal - previousAngle;
                    timeInAngleGoal = 0;

                    if (angleDistance > Mathf.PI || angleDistance < -Mathf.PI)
                    {
                        angleDistance = angleDistance - Mathf.PI * 2;
                    }
                    if (angleDistance > ControllerSettings.JOYSTICK_EMULATOR_ANGLE_DISTANCE_TO_ACTIVATE_COORD_ANIMATION || angleDistance < -ControllerSettings.JOYSTICK_EMULATOR_ANGLE_DISTANCE_TO_ACTIVATE_COORD_ANIMATION)
                    {
                        animationThroughCoords = true;
                        previousPositionVector = new Vector2(Mathf.Cos(previousAngle), Mathf.Sin(previousAngle));
                        newPositionVector      = new Vector2(Mathf.Cos(angleGoal), Mathf.Sin(angleGoal));

                        totalMovementVector = previousPositionVector - newPositionVector;
                        timeLimitOnAngle    = ControllerSettings.JOYSTICK_EMULATOR_COORD_SPEED;
                    }
                    else
                    {
                        animationThroughCoords = false;

                        timeLimitOnAngle = Mathf.Abs(angleDistance) * ControllerSettings.JOYSTICK_EMULATOR_ANIMATION_TIME_PER_RADIAN + Mathf.Epsilon;
                        if (timeLimitOnAngle > ControllerSettings.JOYSTICK_EMULATOR_MAX_ANIMATION_TIME_PER_CHANGE)
                        {
                            timeLimitOnAngle = ControllerSettings.JOYSTICK_EMULATOR_MAX_ANIMATION_TIME_PER_CHANGE;
                        }
                    }
                }
            }
            else
            {
                _joystick.Distance = 0;
                directionalKeysWhereActiveThePreviousFrame = false;
                animationThroughCoords = false;
            }

            float percentageOfAnimation = (timeInAngleGoal / timeLimitOnAngle);

            if (percentageOfAnimation > 1)
            {
                percentageOfAnimation = 1;
            }
            if (animationThroughCoords)
            {
                lastAngle = previousAngle + angleDistance * percentageOfAnimation;
                Vector2 currentPositionVector = previousPositionVector - totalMovementVector * percentageOfAnimation;
                _joystick.Distance = Mathf.Sqrt(currentPositionVector.y * currentPositionVector.y + currentPositionVector.x * currentPositionVector.x);
                _joystick.Angle    = Mathf.Atan2(currentPositionVector.y, currentPositionVector.x);
            }
            else
            {
                if (_joystick.Distance < 1)
                {
                    _joystick.Distance += ControllerSettings.JOYSTICK_EMULATOR_DISTANCE_SPEED * delta;
                    if (_joystick.Distance > 1)
                    {
                        _joystick.Distance = 1;
                    }
                }

                if (percentageOfAnimation >= 1 && !directionalKeys.IsActive())
                {
                    _joystick.Distance = ControllerSettings.JOYSTICK_EMULATOR_MINIUM_DISTANCE_ANGLE_ANIMATION;
                }
                lastAngle       = previousAngle + angleDistance * percentageOfAnimation;
                _joystick.Angle = lastAngle;
            }
            timeInAngleGoal += delta;
        }
Beispiel #16
0
 public static float AngleBetween2D(Vector2 v1, Vector2 v2)
 {
     return(Mathf.Atan2(v2.y - v1.y, v2.x - v1.x) * Mathf.Rad2Deg);
 }
Beispiel #17
0
        public static float As360Angle(this Vector2 inputVector)
        {
            float start = Mathf.Atan2(inputVector.y, inputVector.x);

            return((start > 0 ? start : (2 * Mathf.PI + start)) * 360 / (2 * Mathf.PI));
        }
Beispiel #18
0
    // Update is called once per frame
    void Update()
    {
        if (Input.touchCount == 3)
        {
            Touch t1 = Input.GetTouch(0);
            Touch t2 = Input.GetTouch(1);
            Touch t3 = Input.GetTouch(2);

            bool startTimer = false;

            if (((t1.phase == TouchPhase.Began) || (t2.phase == TouchPhase.Began) || (t3.phase == TouchPhase.Began)) &&
                colorTimer == .5f)
            {
                startTimer = true;

                foreach (GameObject g in walls)
                {
                    if (!wallsAreGreen)
                    {
                        g.GetComponent <Renderer>().material.color = Color.green;
                    }
                    else
                    {
                        g.GetComponent <Renderer>().material.color = Color.magenta;
                    }
                }
            }

            if (startTimer)
            {
                colorTimer -= Time.deltaTime;
            }

            if ((t1.phase == TouchPhase.Ended) || (t2.phase == TouchPhase.Ended) || (t3.phase == TouchPhase.Ended))
            {
                colorTimer    = .5f;
                wallsAreGreen = !wallsAreGreen;
                startTimer    = false;
            }
        }

        if (Input.touchCount == 0)
        {
            timer = .3f;
        }

        if (Input.touchCount > 0)
        {
            holdOrTap = FingerType.Tap;
            timer    -= Time.deltaTime;
            if (timer <= 0)
            {
                holdOrTap = FingerType.Hold;
            }
        }
        if (Input.touchCount == 1)
        {
            timer -= Time.deltaTime;
            Touch firstTouch = Input.GetTouch(0);
            Ray   myRay      = myCamera.ScreenPointToRay(firstTouch.position);
            Debug.DrawRay(myRay.origin, 20 * myRay.direction);
            if (firstTouch.phase == TouchPhase.Moved && holdOrTap == FingerType.Hold && noSelected == 0)
            {
                Debug.Log("Camera should about to move");
                Vector2 touchPosition = firstTouch.deltaPosition;
                myCamera.transform.Translate(-touchPosition.x * cameraMoveSpeed, -touchPosition.y * cameraMoveSpeed, 0);
            }

            RaycastHit infoOnHit;
            if (Physics.Raycast(myRay, out infoOnHit))
            {
                Controllable myScript = infoOnHit.transform.GetComponent <Controllable>();
                if (myScript != selected && holdOrTap == FingerType.Tap)
                {
                    if (noSelected < MAX_SELECTED)
                    {
                        noSelected = MAX_SELECTED;
                        deSelected = myScript;
                        selected   = myScript;
                    }

                    deSelected            = selected;
                    deSelected.isSelected = false;
                    selected            = myScript;
                    selected.isSelected = true;
                    movableObject       = selected.gameObject;

                    dragDistance = Vector3.Distance(movableObject.transform.position, myCamera.transform.position);
                }

                if (noSelected != 0 && holdOrTap == FingerType.Hold)
                {
                    if (firstTouch.phase == TouchPhase.Began)
                    {
                    }

                    if (firstTouch.phase == TouchPhase.Moved)
                    {
                        Ray     dragRay        = myCamera.ScreenPointToRay(firstTouch.position);
                        Vector3 newDestination = dragRay.GetPoint(dragDistance);
                        movableObject.GetComponent <Controllable>().move(newDestination);
                    }

                    if (firstTouch.phase == TouchPhase.Ended)
                    {
                    }
                }
            }
        }

        if (Input.touchCount == 2)
        {
            Touch firstTouch  = Input.GetTouch(0);
            Touch secondTouch = Input.GetTouch(1);

            if (noSelected == 0)
            {
                if (firstTouch.phase == TouchPhase.Began || secondTouch.phase == TouchPhase.Began)
                {
                    initialFirstPos  = firstTouch.position;
                    initialSecondPos = secondTouch.position;
                    initialDistance  = Vector3.Distance(initialFirstPos, initialSecondPos);
                    Vector2 distance = secondTouch.position - firstTouch.position;

                    angleBetweenTouches = Mathf.Atan2(distance.x, distance.y);
                    Quaternion originalRotation = myCamera.transform.rotation;
                }

                if (firstTouch.phase == TouchPhase.Moved || secondTouch.phase == TouchPhase.Moved)
                {
                    Vector3 firstPos          = firstTouch.position;
                    Vector3 secondPos         = secondTouch.position;
                    float   movingDistance    = Vector3.Distance(firstTouch.position, secondTouch.position);
                    float   percentageOfScale = movingDistance / initialDistance;
                    if (percentageOfScale > 1)
                    {
                        myCamera.transform.position += Vector3.forward * (Time.deltaTime * zoomSpeed);
                    }
                    else
                    {
                        myCamera.transform.position -= Vector3.forward * (Time.deltaTime * zoomSpeed);
                    }

                    Vector2 newDistance            = secondTouch.position - firstTouch.position;
                    float   newAngleBetweenTouches = Mathf.Atan2(newDistance.x, newDistance.y);

                    float differenceInAngles = newAngleBetweenTouches - angleBetweenTouches;

                    myCamera.transform.rotation = originalRotation * Quaternion.AngleAxis(Mathf.Rad2Deg * (newAngleBetweenTouches - angleBetweenTouches), myCamera.transform.up);
                }
            }

            else
            {
                if ((firstTouch.phase == TouchPhase.Began) || (secondTouch.phase == TouchPhase.Began))
                {
                    initialFirstPos  = firstTouch.position;
                    initialSecondPos = secondTouch.position;
                    initialDistance  = Vector3.Distance(initialFirstPos, initialSecondPos);

                    Vector2 distance = secondTouch.position - firstTouch.position;

                    angleBetweenTouches = Mathf.Atan2(distance.x, distance.y);
                }

                if ((firstTouch.phase == TouchPhase.Moved || secondTouch.phase == TouchPhase.Moved))
                {
                    Vector3 firstPos          = firstTouch.position;
                    Vector3 secondPos         = secondTouch.position;
                    float   movingDistance    = Vector3.Distance(firstTouch.position, secondTouch.position);
                    float   percentageOfScale = movingDistance / initialDistance;

                    selected.GetComponent <Controllable>().scale(percentageOfScale);

                    Vector2 newDistance            = secondTouch.position - firstTouch.position;
                    float   newAngleBetweenTouches = Mathf.Atan2(newDistance.x, newDistance.y);

                    float differenceInAngles = newAngleBetweenTouches - angleBetweenTouches;

                    selected.GetComponent <Controllable>().rotate(differenceInAngles);
                }
            }
        }
    }
Beispiel #19
0
        public static float GetRotationAnim(Vector3 position, Vector3 desPosition)
        {
            Vector3 distance = desPosition - position;

            return(Mathf.Atan2(distance.y, distance.x) * Mathf.Rad2Deg);
        }
Beispiel #20
0
    public static float GetHorizontalAngle(Vector3 from, Vector3 to)
    {
        Vector3 vector = to - from;

        return((0f - Mathf.Atan2(vector.z, vector.x)) * (180f / Mathf.PI));
    }
Beispiel #21
0
    void FixedUpdate()
    {
        if (Input.touchCount > 0 && Input.touches[0].phase == TouchPhase.Moved)
        {
            //its always x=-1 and y=-1 if touchCount == 0 Resets
            if (deltaPosition.x == -1 && deltaPosition.y == -1)
            {
                deltaPosition = Input.GetTouch(0).position;                                                                       //First touch  point stored
            }
            afterDeltaPosition = Input.GetTouch(0).position;                                                                      //the swiping points
            angle = Mathf.Atan2(afterDeltaPosition.y - deltaPosition.y, afterDeltaPosition.x - deltaPosition.x) * 180 / Mathf.PI; // angle in degrees from 0,-180 and 0,180)
            //Debug.Log("Angle "+ angle);

            if (angle < 45f && angle > -45f)
            {
                SendMessage("JumpAction", 2);
                StartCoroutine(RightCommand(0.02f));
                //Log.text ="Right";
                //if(anim.isPlaying() && anim.CurrentClip.name != "right")
                //{
                //anim.Play("right");

                rigidbody.velocity = (Vector3.right * speed);
                //}
            }
            else if (angle < 135f && angle > 45f)
            {
                /*if(anim.isPlaying() && anim.CurrentClip.name != "front")
                 * {
                 *                          Log.text ="Back";
                 *  //anim.Play("back");
                 *  rigidbody.velocity = (Vector3.up * speed);
                 * }*/
                SendMessage("JumpAction", 2);
                //Log.text ="up";
                //anim.Play("back");
                rigidbody.velocity = (Vector3.up * speed);
            }
            else if (angle > 135f || angle < -135f)
            {
                /*
                 * if(anim.isPlaying() && anim.CurrentClip.name != "left")
                 * {
                 *
                 * //anim.Play("left");
                 * rigidbody.velocity = (Vector3.left * speed);
                 * }*/
                SendMessage("JumpAction", 2);
                StartCoroutine(LeftCommand(0.02f));

                rigidbody.velocity = (Vector3.left * speed);
            }
            else if (angle > -135f && angle < -45f)
            {
                /*if(anim.isPlaying() && anim.CurrentClip.name != "front")
                 * {
                 *
                 * // anim.Play("front");
                 *  rigidbody.velocity = (Vector3.down * speed);
                 * }*/
                //SendMessage("JumpAction", 1);
                //Log.text ="down";
                rigidbody.velocity = (Vector3.down * speed);
            }
        }
        else if (Input.touchCount == 0)
        {
            if (deltaPosition.x != -1 && deltaPosition.y != -1)
            {
                deltaPosition.x = -1;
                deltaPosition.y = -1;
            }
        }
    }
Beispiel #22
0
 // Update is called once per frame
 void Update()
 {
     Debug.Log("ArcTan " + (Mathf.Atan2(y, x) * Mathf.Rad2Deg).ToString());
 }
Beispiel #23
0
    // Update is called once per frame
    void Update()
    {
        //添加 BY:WH
//		win_rect_height=win_rect_width/314*785f;
//		//win_rect = new Rect(-550f, Screen.height - 550f, win_rect_width, win_rect_height);
        handWheelPlaneRect = new Rect(hand_x, hand_y, hand_width, hand_height);
        handWheelOrigin    = new Vector2(handWheelOrigin_x, handWheelOrigin_y);
        num_height         = num_width / 416 * 502;

        //Debug.Log("ccc");
        Vector3 mousePos = Input.mousePosition;

        //Debug.Log(Screen.height-mousePos.y);
        //mousePos.y=Screen.height-mousePos.y;
        //Debug.Log(handWheelAreaRect);
        //Debug.Log(handWheelRect);
        //Debug.Log(mousePos);

        //Debug.Log(mousePos.x+"mpppp"+win_rect.x);
        //Debug.Log(win_rect.x+"we");
        mousePos.x -= win_rect.x;
        mousePos.y  = Screen.height - mousePos.y;
        mousePos.y -= win_rect.y;
        //Debug.Log("Ok~~"+mousePos.x+" "+mousePos.y);
        //float distance=(mousePos.x-handWheelOrigin.x)*(mousePos.x-handWheelOrigin.x)+(mousePos.y-handWheelOrigin.y)*(mousePos.y-handWheelOrigin.y);
        if (handWheelAreaRect.Contains(mousePos))
        //distance=Mathf.Pow (distance,0.5f);
        //if(distance>minDistance&&distance<maxDistance)
        {
            //Debug.Log("Ok~~"+mousePos.x+" "+mousePos.y);
            if (Input.GetMouseButtonDown(0))
            {
                //Debug.Log(mousePos);
                if (!initializeAngleOffset)
                {
                    angleOffset     = 180 - Mathf.Atan2(mousePos.x - handWheelOrigin.x, mousePos.y - handWheelOrigin.y) * Mathf.Rad2Deg;
                    currRotateAngle = angleOffset;

                    //currRotateAngle=angleOffset;
                    initializeAngleOffset = true;
                }

                //	mousePos.y=Screen.height-mousePos.y;
                //Debug.Log(mousePos);


                if (!initializeLastPos)
                {
                    lastMousePos      = mousePos;
                    initializeLastPos = true;
                    // Debug.Log("shubiao click");
                }

                handWheelActive = true;
            }

            if (Input.GetMouseButtonUp(0))
            {
                if (handWheelActive)
                {
                    rotatedAngle         += currRotateAngle - angleOffset;
                    handWheelActive       = false;
                    initializeLastPos     = false;
                    initializeAngleOffset = false;
                }

                //	sumAngle=0;
            }
        }
        else
        {
            //if(Input.GetMouseButtonUp(0))
            if (handWheelActive)
            {
                rotatedAngle += currRotateAngle - angleOffset;
            }
            // rotatedAngle+=currRotateAngle-angleOffset;
            //rotatedAngle+=currRotateAngle-angleOffset;
            handWheelActive       = false;
            initializeLastPos     = false;
            initializeAngleOffset = false;
            //rotatedAngle+=sumAngle;
            ////  sumAngle=0;
            //Debug.Log(handWheelAreaRect);
        }
    }
Beispiel #24
0
        private void FixedUpdate()
        {
            if (m_Target == null || !m_Driving)
            {
                // Car should not be moving,
                // use handbrake to stop
                m_CarController.Move(0, 0, -1f, 1f);
            }
            else
            {
                Vector3 fwd = transform.forward;
                if (m_Rigidbody.velocity.magnitude > m_CarController.MaxSpeed * 0.1f)
                {
                    fwd = m_Rigidbody.velocity;
                }
                float desiredSpeed = m_CarController.MaxSpeed;
                // now it's time to decide if we should be slowing down...
                switch (m_BrakeCondition)
                {
                case BrakeCondition.TargetDirectionDifference:
                {
                    // the car will brake according to the upcoming change in direction of the target. Useful for route-based AI, slowing for corners.

                    // check out the angle of our target compared to the current direction of the car
                    float approachingCornerAngle = Vector3.Angle(m_Target.forward, fwd);

                    // also consider the current amount we're turning, multiplied up and then compared in the same way as an upcoming corner angle
                    float spinningAngle = m_Rigidbody.angularVelocity.magnitude * m_CautiousAngularVelocityFactor;

                    // if it's different to our current angle, we need to be cautious (i.e. slow down) a certain amount
                    float cautiousnessRequired = Mathf.InverseLerp(0, m_CautiousMaxAngle,
                                                                   Mathf.Max(spinningAngle,
                                                                             approachingCornerAngle));
                    desiredSpeed = Mathf.Lerp(m_CarController.MaxSpeed, m_CarController.MaxSpeed * m_CautiousSpeedFactor,
                                              cautiousnessRequired);
                    break;
                }

                case BrakeCondition.TargetDistance:
                {
                    // the car will brake as it approaches its target, regardless of the target's direction. Useful if you want the car to
                    // head for a stationary target and come to rest when it arrives there.

                    // check out the distance to target
                    Vector3 delta = m_Target.position - transform.position;
                    float   distanceCautiousFactor = Mathf.InverseLerp(m_CautiousMaxDistance, 0, delta.magnitude);

                    // also consider the current amount we're turning, multiplied up and then compared in the same way as an upcoming corner angle
                    float spinningAngle = m_Rigidbody.angularVelocity.magnitude * m_CautiousAngularVelocityFactor;

                    // if it's different to our current angle, we need to be cautious (i.e. slow down) a certain amount
                    float cautiousnessRequired = Mathf.Max(
                        Mathf.InverseLerp(0, m_CautiousMaxAngle, spinningAngle), distanceCautiousFactor);
                    desiredSpeed = Mathf.Lerp(m_CarController.MaxSpeed, m_CarController.MaxSpeed * m_CautiousSpeedFactor,
                                              cautiousnessRequired);
                    break;
                }

                case BrakeCondition.NeverBrake:
                    break;
                }

                // Evasive action due to collision with other cars:

                // our target position starts off as the 'real' target position
                Vector3 offsetTargetPos = m_Target.position;

                // if are we currently taking evasive action to prevent being stuck against another car:
                if (Time.time < m_AvoidOtherCarTime)
                {
                    // slow down if necessary (if we were behind the other car when collision occured)
                    desiredSpeed *= m_AvoidOtherCarSlowdown;

                    // and veer towards the side of our path-to-target that is away from the other car
                    //          offsetTargetPos += m_Target.right*m_AvoidPathOffset;
                }
                else
                {
                    // no need for evasive action, we can just wander across the path-to-target in a random way,
                    // which can help prevent AI from seeming too uniform and robotic in their driving
                    //              offsetTargetPos += m_Target.right*
                    //                               (Mathf.PerlinNoise(Time.time*m_LateralWanderSpeed, m_RandomPerlin)*2 - 1)*
                    //                             m_LateralWanderDistance;
                }

                // use different sensitivity depending on whether accelerating or braking:
                float accelBrakeSensitivity = (desiredSpeed < m_CarController.CurrentSpeed)
                                                  ? m_BrakeSensitivity
                                                  : m_AccelSensitivity;

                // decide the actual amount of accel/brake input to achieve desired speed.
                float accel = Mathf.Clamp((desiredSpeed - m_CarController.CurrentSpeed) * accelBrakeSensitivity, -1, 1);

                // add acceleration 'wander', which also prevents AI from seeming too uniform and robotic in their driving
                // i.e. increasing the accel wander amount can introduce jostling and bumps between AI cars in a race
                accel *= (1 - m_AccelWanderAmount) +
                         (Mathf.PerlinNoise(Time.time * m_AccelWanderSpeed, m_RandomPerlin) * m_AccelWanderAmount);

                // calculate the local-relative position of the target, to steer towards
                Vector3 localTarget = transform.InverseTransformPoint(offsetTargetPos);

                // work out the local angle towards the target
                float targetAngle = Mathf.Atan2(localTarget.x, localTarget.z) * Mathf.Rad2Deg;

                // get the amount of steering needed to aim the car towards the target
                float steer = Mathf.Clamp(targetAngle * m_SteerSensitivity, -1, 1) * Mathf.Sign(m_CarController.CurrentSpeed);

                // feed input to the car controller.
                m_CarController.Move(steer, accel, accel, 0f);

                // if appropriate, stop driving when we're close enough to the target.
                if (m_StopWhenTargetReached && localTarget.magnitude < m_ReachTargetThreshold)
                {
                    m_Driving = false;
                }
            }
        }
Beispiel #25
0
 void RotateTurret()
 {
     rotator.eulerAngles = new Vector3(0, Mathf.Atan2(input.x, input.y) * 180 / Mathf.PI, 0);
 }
Beispiel #26
0
        public override void Draw(DrawingContext drawingContext, float scale, float x, float y)
        {
            base.Draw(drawingContext, scale, x, y);
            PrepareDraw(drawingContext);

            //This is for people who are nerdy about math
            float op = Mathf.Max(0, offsetPlus), om = Mathf.Min(0, offsetMinus);
            float opm = op - om;
            float angle;

            switch (mode)
            {
            case StrikeMode.diagonal: angle = Mathf.Atan2(totalHeight + margin * 2 - opm, width); break;

            case StrikeMode.diagonalInverse: angle = Mathf.Atan2(totalHeight + margin * 2 - opm, width); break;

            case StrikeMode.vertical: angle = Mathf.Atan2(totalHeight + margin * 2, width - opm); break;

            case StrikeMode.verticalInverse: angle = Mathf.Atan2(totalHeight + margin * 2, width - opm); break;

            default: angle = 0; break;
            }
            float s = Mathf.Sin(angle) * thickness, c = Mathf.Cos(angle) * thickness;
            float w = width, ww = width + margin, h = totalHeight / 2f + margin;

            Vector2[] v = new Vector2[4];
            y += totalHeight / 2f - depth;
            if ((int)mode > 1 && (int)mode < 6)
            {
                y += op + om;
            }
            switch (mode)
            {
            case StrikeMode.diagonal:
                v[0] = new Vector2((x + w + s) * scale, (y + h - c + om) * scale); //Top-Left
                v[1] = new Vector2((x + w - s) * scale, (y + h + c + om) * scale); //Top-Right
                v[2] = new Vector2((x - s) * scale, (y - h + c + op) * scale);     //Bottom-Right
                v[3] = new Vector2((x + s) * scale, (y - h - c + op) * scale);     //Bottom-Left
                break;

            case StrikeMode.diagonalInverse:
                v[0] = new Vector2((x + s) * scale, (y + h + c + om) * scale);     //Top-Left
                v[1] = new Vector2((x - s) * scale, (y + h - c + om) * scale);     //Top-Right
                v[2] = new Vector2((x + w - s) * scale, (y - h - c + op) * scale); //Bottom-Right
                v[3] = new Vector2((x + w + s) * scale, (y - h + c + op) * scale); //Bottom-Left
                break;

            case StrikeMode.horizontal:
                y   += TEXConfiguration.main.MiddleLineOffset;
                v[0] = new Vector2((x - margin) * scale, (y + thickness) * scale); //Top-Left
                v[1] = new Vector2((x + ww) * scale, (y + thickness) * scale);     //Top-Right
                v[2] = new Vector2((x + ww) * scale, (y - thickness) * scale);     //Bottom-Right
                v[3] = new Vector2((x - margin) * scale, (y - thickness) * scale); //Bottom-Left
                break;

            case StrikeMode.doubleHorizontal:
                float doubleOffset = TEXConfiguration.main.DoubleNegateMargin;
                y   += TEXConfiguration.main.MiddleLineOffset;
                v[0] = new Vector2((x - margin) * scale, (y + thickness + doubleOffset) * scale); //Top-Left
                v[1] = new Vector2((x + ww) * scale, (y + thickness + doubleOffset) * scale);     //Top-Right
                v[2] = new Vector2((x + ww) * scale, (y - thickness + doubleOffset) * scale);     //Bottom-Right
                v[3] = new Vector2((x - margin) * scale, (y - thickness + doubleOffset) * scale); //Bottom-Left
                Draw(drawingContext, v);

                v[0] = new Vector2((x - margin) * scale, (y + thickness - doubleOffset) * scale); //Top-Left
                v[1] = new Vector2((x + ww) * scale, (y + thickness - doubleOffset) * scale);     //Top-Right
                v[2] = new Vector2((x + ww) * scale, (y - thickness - doubleOffset) * scale);     //Bottom-Right
                v[3] = new Vector2((x - margin) * scale, (y - thickness - doubleOffset) * scale); //Bottom-Left
                break;

            case StrikeMode.underline:
                y   -= totalHeight / 2f - depth + thickness * 2 - TEXConfiguration.main.UnderLineOffset;
                v[0] = new Vector2((x - margin) * scale, (y + thickness) * scale); //Top-Left
                v[1] = new Vector2((x + ww) * scale, (y + thickness) * scale);     //Top-Right
                v[2] = new Vector2((x + ww) * scale, (y - thickness) * scale);     //Bottom-Right
                v[3] = new Vector2((x - margin) * scale, (y - thickness) * scale); //Bottom-Left
                break;

            case StrikeMode.overline:
                y   += totalHeight / 2 + thickness * 2 + TEXConfiguration.main.OverLineOffset;
                v[0] = new Vector2((x - margin) * scale, (y + thickness) * scale); //Top-Left
                v[1] = new Vector2((x + ww) * scale, (y + thickness) * scale);     //Top-Right
                v[2] = new Vector2((x + ww) * scale, (y - thickness) * scale);     //Bottom-Right
                v[3] = new Vector2((x - margin) * scale, (y - thickness) * scale); //Bottom-Left
                break;

            case StrikeMode.vertical:
                v[0] = new Vector2((x + w + s + om) * scale, (y + h - c) * scale); //Top-Left
                v[1] = new Vector2((x + w - s + om) * scale, (y + h + c) * scale); //Top-Right
                v[2] = new Vector2((x - s + op) * scale, (y - h + c) * scale);     //Bottom-Right
                v[3] = new Vector2((x + s + op) * scale, (y - h - c) * scale);     //Bottom-Left
                break;

            case StrikeMode.verticalInverse:
                v[0] = new Vector2((x + s + op) * scale, (y + h + c) * scale);     //Top-Left
                v[1] = new Vector2((x - s + op) * scale, (y + h - c) * scale);     //Top-Right
                v[2] = new Vector2((x + w - s + om) * scale, (y - h - c) * scale); //Bottom-Right
                v[3] = new Vector2((x + w + s + om) * scale, (y - h + c) * scale); //Bottom-Left
                break;
            }
            Draw(drawingContext, v);
        }
Beispiel #27
0
    void Update()
    {
        //create rotation
        //Quaternion wantedRotation = Quaternion.LookRotation(new Vector3(Input.GetTouch(0).position.x, Input.GetTouch(0).position.y, 0) - player.position);
        //Quaternion wantedRotation = Quaternion.LookRotation(Input.GetTouch(0).position - new Vector2(player.position.x, player.position.y));
        //Debug.Log(SceneManager.GetActiveScene().name);
        if (Input.touchCount > 0 && (Input.GetTouch(0).phase == TouchPhase.Moved || Input.GetTouch(0).phase == TouchPhase.Stationary))
        {
            Vector3 mouse_pos;
            Vector3 object_pos;

            // Debug.Log("OG Pos: " + transform.position);
            // Transform newOrigin = transform;
            //newOrigin.position += new Vector3(GetComponent<Renderer>().bounds.size.x / 2, GetComponent<Renderer>().bounds.size.y / 2, GetComponent<Renderer>().bounds.size.z);
            //newOrigin.loca
            //Debug.Log("New Pos: " + newOrigin.position);
            //Debug.Log("OG Pos After: " + transform.position);

            //GameObject newO = new GameObject();
            //newO.transform.localPosition = transform.localPosition;
            // newO.transform.localRotation = transform.localRotation;
            // newO.transform.localScale = transform.localScale;
            //newO.transform.position = transform.position;
            //newO.transform.rotation = transform.rotation;
            //newO.transform.localScale = transform.localScale;

            //newO.transform.Translate(new Vector3(GetComponent<Renderer>().bounds.size.x / 2, GetComponent<Renderer>().bounds.size.y / 2, 0));
            //Debug.Log("Position" + transform.position);

            mouse_pos   = Input.GetTouch(0).position;
            mouse_pos.z = 1;     //The distance between the camera and object
            object_pos  = Camera.main.WorldToScreenPoint(transform.position);
            mouse_pos.x = mouse_pos.x - object_pos.x;
            mouse_pos.y = mouse_pos.y - object_pos.y;
            float      degree = Mathf.Atan2(mouse_pos.y, mouse_pos.x) * Mathf.Rad2Deg;
            Quaternion angle  = Quaternion.Euler(0, 0, degree - 90);

            // Debug.Log("NE" + (Mathf.Atan2(mouse_pos.y, mouse_pos.x) * Mathf.Rad2Deg));

            //transform.RotateAround(newO.position, transform.forward, (Mathf.Atan2(mouse_pos.y, mouse_pos.x) * Mathf.Rad2Deg * Time.deltaTime - 90));
            //Debug.Log("BOI" + newO.transform.position);

            if (!advancedRotation)
            {
                transform.rotation = Quaternion.Lerp(transform.rotation, angle, ((rotationSpeed - 1) / 2 + 1));
            }


            //then rotate
            if (advancedMovement || advancedRotation)
            {
                if (degree < 0)
                {
                    degree = 360 - degree * -1;
                }
                degree -= 90;
                if (degree < 0)
                {
                    degree = 360 - degree * -1;
                }
            }

            if (advancedRotation)
            {
                float eul = transform.eulerAngles.z;
                if (eul < degree)
                {
                    eul += 360;
                }

                float reld = eul - degree;
                float dif  = transform.eulerAngles.z - degree;
                if (reld < 180)
                {
                    GetComponent <Rigidbody2D>().AddTorque(((2 * Mathf.Pow((reld / 180), 2)) + 0.02F) * -5000 * ((rotationSpeed - 1) / 4 + 1) * Time.deltaTime * 100);
                }
                else
                {
                    GetComponent <Rigidbody2D>().AddTorque(((2 * Mathf.Pow(Mathf.Abs(180 - (reld - 180)) / 180, 2)) + 0.02F) * 5000 * ((rotationSpeed - 1) / 2 + 1) * Time.deltaTime * 100);
                }
            }



            //Debug.Log("DEG " + (degree) + " EUL " + eul + " RELD " + reld);

            //Vector3 oldRot = transform.rotation.eulerAngles; transform.rotation = Quaternion.Euler(0, 0, oldRot.z);
            if (advancedMovement)
            {
                GetComponent <Rigidbody2D>().AddForce(new Vector2(Mathf.Cos((degree + 90) * Mathf.Deg2Rad), Mathf.Sin((degree + 90) * Mathf.Deg2Rad)) * ((movementSpeed - 1) / 4 + 1) * 100 * Time.deltaTime * 100 * 0.8F);
            }
            else
            {
                transform.position += transform.up * Time.deltaTime * movementSpeed * 100 * 0.8F;
            }
        }
        else if (Input.GetMouseButton(0))
        {
            Vector3 mouse_pos;
            Vector3 object_pos;

            // Debug.Log("OG Pos: " + transform.position);
            // Transform newOrigin = transform;
            //newOrigin.position += new Vector3(GetComponent<Renderer>().bounds.size.x / 2, GetComponent<Renderer>().bounds.size.y / 2, GetComponent<Renderer>().bounds.size.z);
            //newOrigin.loca
            //Debug.Log("New Pos: " + newOrigin.position);
            //Debug.Log("OG Pos After: " + transform.position);

            //GameObject newO = new GameObject();
            //newO.transform.localPosition = transform.localPosition;
            // newO.transform.localRotation = transform.localRotation;
            // newO.transform.localScale = transform.localScale;
            //newO.transform.position = transform.position;
            //newO.transform.rotation = transform.rotation;
            //newO.transform.localScale = transform.localScale;

            //newO.transform.Translate(new Vector3(GetComponent<Renderer>().bounds.size.x / 2, GetComponent<Renderer>().bounds.size.y / 2, 0));
            //Debug.Log("Position" + transform.position);

            mouse_pos   = Input.mousePosition;
            mouse_pos.z = 1;     //The distance between the camera and object
            object_pos  = Camera.main.WorldToScreenPoint(transform.position);
            mouse_pos.x = mouse_pos.x - object_pos.x;
            mouse_pos.y = mouse_pos.y - object_pos.y;
            float      degree = Mathf.Atan2(mouse_pos.y, mouse_pos.x) * Mathf.Rad2Deg;
            Quaternion angle  = Quaternion.Euler(0, 0, degree - 90);

            // Debug.Log("NE" + (Mathf.Atan2(mouse_pos.y, mouse_pos.x) * Mathf.Rad2Deg));

            //transform.RotateAround(newO.position, transform.forward, (Mathf.Atan2(mouse_pos.y, mouse_pos.x) * Mathf.Rad2Deg * Time.deltaTime - 90));
            //Debug.Log("BOI" + newO.transform.position);

            if (!advancedRotation)
            {
                transform.rotation = Quaternion.Lerp(transform.rotation, angle, ((rotationSpeed - 1) / 2 + 1));
            }


            //then rotate
            if (advancedMovement || advancedRotation)
            {
                if (degree < 0)
                {
                    degree = 360 - degree * -1;
                }
                degree -= 90;
                if (degree < 0)
                {
                    degree = 360 - degree * -1;
                }
            }

            if (advancedRotation)
            {
                float eul = transform.eulerAngles.z;
                if (eul < degree)
                {
                    eul += 360;
                }

                float reld = eul - degree;
                float dif  = transform.eulerAngles.z - degree;
                if (reld < 180)
                {
                    GetComponent <Rigidbody2D>().AddTorque(((2 * Mathf.Pow((reld / 180), 2)) + 0.02F) * -5000 * ((rotationSpeed - 1) / 2 + 1) * Time.deltaTime * 100);
                }
                else
                {
                    GetComponent <Rigidbody2D>().AddTorque(((2 * Mathf.Pow(Mathf.Abs(180 - (reld - 180)) / 180, 2)) + 0.02F) * 5000 * ((rotationSpeed - 1) / 2 + 1) * Time.deltaTime * 100);
                }
            }



            //Debug.Log("DEG " + (degree) + " EUL " + eul + " RELD " + reld);

            //Vector3 oldRot = transform.rotation.eulerAngles; transform.rotation = Quaternion.Euler(0, 0, oldRot.z);
            if (advancedMovement)
            {
                GetComponent <Rigidbody2D>().AddForce(new Vector2(Mathf.Cos((degree + 90) * Mathf.Deg2Rad), Mathf.Sin((degree + 90) * Mathf.Deg2Rad)) * ((movementSpeed - 1) / 4 + 1) * 100 * Time.deltaTime * 100 * 0.8F);
            }
            else
            {
                transform.position += transform.up * Time.deltaTime * movementSpeed * 100 * 0.8F;
            }
        }
    }
Beispiel #28
0
    float GetProperAngle(Vector2 _objPos, Vector2 _inputPos)
    {
        float finalAngle = 180 + Mathf.Atan2(_objPos.y - _inputPos.y, _objPos.x - _inputPos.x) * Mathf.Rad2Deg;

        return(finalAngle);
    }
Beispiel #29
0
        public static float AngleFromTo(Vector2 src, Vector2 target)
        {
            Vector2 diff = target - src;

            return(Mathf.Atan2(diff.y, diff.x));
        }
Beispiel #30
0
 internal Vector2 GetDirDegMag()
 {
     return(new Vector2(Mathf.Atan2(xY.y, xY.x), xY.magnitude));
 }