// Update is called once per frame void FixedUpdate () { if (moveBody != null && targetWaypoint < waypoints.Length) { Vector2 oldWayPos; if (targetWaypoint == 0) oldWayPos = Vector2.zero; else oldWayPos = new Vector2(waypoints[targetWaypoint - 1].x, waypoints[targetWaypoint - 1].y); Vector2 newPosition = new Vector2(waypoints[targetWaypoint].x, waypoints[targetWaypoint].y) - oldWayPos; if (isMoving)//We are on way from one waypoint to another, shouldn't miss it { if ((moveBody.position - oldPosition).SqrMagnitude() > newPosition.SqrMagnitude()) { isMoving = false; //moveBody.velocity = Vector2.zero; targetWaypoint++; } } else//Let's find another waypoint! { oldPosition = moveBody.position; newPosition.Normalize(); Vector2 velocity = newPosition * waypoints[targetWaypoint].z; moveBody.velocity = velocity; isMoving = true; } } }
// Update is called once per frame void Update() { if (Application.platform == RuntimePlatform.Android || Application.platform == RuntimePlatform.IPhonePlayer || Application.platform == RuntimePlatform.MetroPlayerARM) { touchRay = Camera.main.ScreenPointToRay(Input.GetTouch(0).position); if (Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Began ) { if (touchRay.origin.x >= -4.8f && touchRay.origin.x <= 0.6f && touchRay.origin.y >= -1.5f && touchRay.origin.y <= 3.5f) { // 起點落在摩天輪的範圍內 m_PrevPos.x = touchRay.origin.x; m_PrevPos.y = touchRay.origin.y; m_bMovinWheel = true; } } else if (Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Moved) { // 根據拖曳的順逆時方向來設定轉動的方向, 根據移動的差距來計算轉動的角度 if (touchRay.origin.x >= -4.8f && touchRay.origin.x <= 0.6f && touchRay.origin.y >= -1.5f && touchRay.origin.y <= 3.5f) { m_CurrPos.x = touchRay.origin.x; m_CurrPos.y = touchRay.origin.y; float px, py, nx, ny, t; px = m_PrevPos.x - m_FWCenter.x; // 摩天輪中心指向前一個 TP 的向量 py = m_PrevPos.y - m_FWCenter.y; nx = m_CurrPos.x - m_FWCenter.x; // 摩天輪中心指向目前 TP 的向量 ny = m_CurrPos.y - m_FWCenter.y; m_t = px * ny - py * nx; // (px,py) 與 (nx, ny) 的外積, > 0 代表逆時針, < 0 代表順時針 m_TPDelta = Input.GetTouch(0).deltaPosition; if (m_t >= 0) m_fdegree = -m_TPDelta.SqrMagnitude()*1.5f; else m_fdegree = m_TPDelta.SqrMagnitude() * 1.5f; transform.Rotate(0, m_fdegree, 0); for (int i = 0; i < 8; i++) m_CarScript[i].SetDegree(m_fdegree); // 有呼叫才需要轉動一次, 採用一步到位的方式執行? m_fdegree = 0; m_PrevPos = m_CurrPos; } else { if (m_bMovinWheel) m_bMovinWheel = false; } } else { if( m_bMovinWheel ) m_bMovinWheel = false; } } }
//save the left and right stick input axes to Vector2s and give them to 'input' public void GetInput(ref PlayerInput input) { Vector2 leftStickInput = new Vector2(Input.GetAxis("L_XAxis_" + myPlayer.playerNo), Input.GetAxis("L_YAxis_" + myPlayer.playerNo)); Vector2 rightStickInput = new Vector2(Input.GetAxis("R_XAxis_" + myPlayer.playerNo), Input.GetAxis("R_YAxis_" + myPlayer.playerNo)); if(leftStickInput.SqrMagnitude() > (ANALOGUE_STICK_THRESHOLD * ANALOGUE_STICK_THRESHOLD)) { input.SetMovement(leftStickInput); } else { input.SetMovement(Vector2.zero); } if(rightStickInput.SqrMagnitude() > (ANALOGUE_STICK_THRESHOLD * ANALOGUE_STICK_THRESHOLD)) { input.SetAim(rightStickInput); } else { input.SetAim(Vector2.zero); } //check if the right trigger is pressed bool action = Input.GetAxis("TriggersR_" + myPlayer.playerNo) > TRIGGERS_THRESHOLD ? true : false; //if action was false and is now true, set actionDown to true if(!input.GetAction() && action) { input.SetActionDown(true); } else { //otherwise actionDown is false input.SetActionDown(false); } //check if the left trigger is pressed bool secondaryAction = Input.GetAxis("TriggersL_" + myPlayer.playerNo) > TRIGGERS_THRESHOLD ? true : false; //if secondaryAction was false and is now true, set secondaryActionDown to true if (!input.GetSecondaryAction() && secondaryAction) { input.SetSecondaryActionDown(true); } else { //otherwise secondaryActionDown is false input.SetSecondaryActionDown(false); } input.SetAction(action); input.SetSecondaryAction(secondaryAction); }
public override Vector2 CalculateMove(FlockAgent agent, List <Transform> context, Flock flock) { if (context.Count == 0) { return(agent.transform.up); } Vector2 avoidanceMove = Vector2.zero; int nAvoid = 0; List <Transform> filteredContext = (filter == null) ? context : filter.Filter(agent, context); foreach (Transform item in filteredContext) { if (Vector2.SqrMagnitude(item.position - agent.transform.position) < flock.getSqrAvoidanceRadius) { nAvoid++; avoidanceMove += (Vector2)(agent.transform.position - item.position); } } if (nAvoid > 0) { avoidanceMove /= nAvoid; } return(avoidanceMove); }
/* * Returns the acceleration due to gravity from a set of celestial bodies * (Note: This does NOT return the force, just the acceleration) */ private Vector2 gravity(GameObject[] bodies) { //Called a force here for convenience, really an acceleration Vector2 totalForce = Vector2.zero; //Calculate and sum each force from each planet foreach (GameObject planet in bodies) { Planet p = planet.GetComponent <Planet>(); if (p != null) { Vector2 radius = planet.transform.position - this.transform.position; double magRadius = Math.Sqrt(Vector2.SqrMagnitude(radius)); //If we are sufficiently far away from the center of the planet, calculate the force if (magRadius >= closestApproach) { Vector2 force = (float)(G * p.getMass() / Math.Pow(magRadius, 3)) * radius; totalForce += force; }//else, do nothing (this keeps divide by 0 errors from happening) } } return(totalForce); }
/// <summary> /// Gets the country that contains a given map coordinate or the country whose center is nearest to that coordinate. /// </summary> public int GetCountryNearPoint(Vector2 localPosition) { int countryIndex = GetCountryIndex(localPosition); if (countryIndex >= 0) { return(countryIndex); } float minDist = float.MaxValue; int countryCount = _countriesOrderedBySize.Count; for (int k = 0; k < countryCount; k++) { int oc = _countriesOrderedBySize[k]; Country country = countries[oc]; float dist = Vector2.SqrMagnitude(country.center - localPosition); if (dist < minDist) { minDist = dist; countryIndex = k; } } return(countryIndex); }
public bool UpdateInput() { int count = 0; #if UNITY_STANDALONE_WIN || UNITY_EDITOR if (Input.GetMouseButton(0)) { count = 1; } #else count = Input.touchCount; #endif if (!processInput) { return(false); } if (working && Camera.main != null) { dirCam = Camera.main.transform.forward; dirCam.y = 0.0f; dirCam.Normalize(); noWorkingTimer = 0.0f; working = false; if (count > 0) { Vector2 touchPos = Vector2.zero; for (int i = 0; i < count; i++) { #if UNITY_STANDALONE_WIN || UNITY_EDITOR if (i == 0) { touchPos.x = Input.mousePosition.x; touchPos.y = Input.mousePosition.y; } #else Touch touch = Input.GetTouch(i); touchPos = touch.position; #endif touchPos.y = CoreEntry.screenHeight - touchPos.y; if ((lastTouchPos - touchPos).magnitude < 200.0f) { thumbPos = touchPos; Vector2 vThumbDir = thumbPos - initPos; vThumbDir.Normalize(); vThumbDir.y = -vThumbDir.y; dirRight = Vector3.Cross(Vector3.up, dirCam); Vector3 vMoveDir = dirCam * vThumbDir.y * Time.deltaTime * 4.0f; vMoveDir += dirRight * vThumbDir.x * Time.deltaTime * 4.0f; vMoveDir.Normalize(); joystickDir = vMoveDir; joystickDir2 = touchPos - initPos2; // 计算拇指位置距离摇杆中心点距离,如果小于阈值,改变计算摇杆方向的方式 Vector2 diff = touchPos - initPos; float dist = Vector2.SqrMagnitude(diff); if (dist <= moveDistanceThreshold * moveDistanceThreshold) { inMiniCircle = true; //panel.thumb.GetComponent<UISprite>().color = Color.red; } else { inMiniCircle = false; //panel.thumb.GetComponent<UISprite>().color = Color.white; } //Debug.LogError("touchpos:" + touchPos + "initpos:" + initPos + "dist to initpos:" + Vector2.ClampMagnitude(diff,1000f)); if (m_callbackMove != null) { m_callbackMove(vMoveDir); } if (m_callbackMoveRelative != null) { m_callbackMoveRelative(joystickDir2); } lastTouchPos = touchPos; working = true; break; } } } if (working == false) { ResetInitPos(); ResetInitPos2(); EventMgr.instance.TriggerEvent("joystickInitPosReset"); thumbPos = initPos; if (m_callbackStop != null) { m_callbackStop(); } } } else { noWorkingTimer += Time.deltaTime; if (count == 0) { checkWorking = false; } else { Vector2 touchPos = Vector2.zero; for (int i = 0; i < count; i++) { #if UNITY_STANDALONE_WIN || UNITY_EDITOR if (i == 0) { touchPos.x = Input.mousePosition.x; touchPos.y = Input.mousePosition.y; } #else Touch touch = Input.GetTouch(i); touchPos = touch.position; #endif touchPos.y = CoreEntry.screenHeight - touchPos.y; if (InputMgr.instance.inputControlMode == InputControlMode.Normal || InputMgr.instance.inputControlMode == InputControlMode.InitStatic) { if (IsPointInStaticArea(touchPos)) { if (checkWorking) { if ((touchPos - initPos).magnitude > workingMagnitude) { working = true; checkWorking = false; } } else { checkWorking = true; initPos = touchPos; initPos2 = touchPos; EventMgr.instance.TriggerEvent("joystickInitPosReset"); } lastTouchPos = touchPos; thumbPos = touchPos; break; } } else if (InputMgr.instance.inputControlMode == InputControlMode.Static) { if (IsPointInWorkingArea(touchPos)) { if (checkWorking) { working = true; checkWorking = false; } else { checkWorking = true; EventMgr.instance.TriggerEvent("joystickInitPosReset"); } lastTouchPos = touchPos; break; } } } } } OnDraw(); return(working); }
// Update is called once per frame void Update() { UpdateScore(); if (rayOn) { RaycastHit hit; Physics.Raycast(transform.position, transform.forward, out hit); //Vector3 cursorPosition = new Vector3(cursor.transform.position.x, hit.transform.position.y, hit.transform.position.z); if (Input.GetKeyDown(KeyCode.Tab)) Debug.Log("hi"); //cursor.transform.position = cursorPosition; } // void establish from state() if (app.RespectMyAutoritah() && !myBall) { ghostBall.SetActive(true); if (usingWiimote) { int ret; float velocity_old = 0.0f; ret = wiiController.ReadWiimoteData(); wiiButton = wiiController.Button; if (ret > 0 && wiiButton.b) { oldVecz = newVecz; throwSet = true; Vector3 accel = GetAccelVector(); Vector3 accelNormal = accel; accelNormal.Normalize(); float sizeOfWidth = 2; leftRightMotion = accelNormal.x * (sizeOfWidth / 2); velocity_old = velocity; Vector2 vVec = new Vector2(accel.y, accel.z); velocity = Mathf.Sqrt(vVec.SqrMagnitude()); velocity *= Mathf.Sign(accel.y); velocity -= velocity_old; newVecz = leftRightMotion; if (finalVel >= velocity) { finalVel = velocity; fVelTime = Time.time; } iTween.ValueTo(gameObject, iTween.Hash("from", oldVecz, "to", newVecz, "time", Time.deltaTime * 4.0f, "onupdate", "ShowGhost")); Debug.Log(finalVel); } else if (!wiiButton.b && throwSet) { throwSet = false; Destroy(myBall); myBallPos = new Vector3(transform.position.x - 1, transform.position.y, newVecz); myBallVel = new Vector3(Mathf.Min(finalVel, 0) * 2, 2f, newVecz / 100); myBall = (GameObject)Instantiate(pingPong, myBallPos, Quaternion.identity); myBall.GetComponent<Rigidbody>().velocity = myBallVel; Debug.Log(finalVel); myBall.GetComponent<BallBehavior>().setApp(this); myBall.GetComponent<BallBehavior>().EnablePlay(); finalVel = 0; velocity = 0; } if (Time.time - fVelTime > 1f) { finalVel = velocity; fVelTime = Time.time; } } else if (Input.GetKeyDown(KeyCode.Space)) { myBall = (GameObject)Instantiate(pingPong, new Vector3(transform.position.x - 1, transform.position.y, 0), Quaternion.identity); myBall.GetComponent<Rigidbody>().velocity = new Vector3(-7.2f, 2f, 0f); myBall.GetComponent<BallBehavior>().setApp(this); myBall.GetComponent<BallBehavior>().EnablePlay(); } if (Time.time - timeStart > 30f && playEnabled && false) { TimeUp(); } } else { ghostBall.SetActive(false); } }
public void Select(Transform transform, Vector2 mousePos, Camera camera, out int selVertex, out int selFace, out UnorderedPair <int> selEdge, float radius = 10, float bump = 0.2f) { selVertex = -1; selFace = -1; selEdge = new UnorderedPair <int>(-1, -1); float minDist = Mathf.Infinity; Ray ray = camera.ScreenPointToRay(mousePos); ray.origin = transform.InverseTransformPoint(ray.origin); ray.direction = transform.InverseTransformDirection(ray.direction); for (int v = 0; v < vertices.Count; v++) { Vertex vert = vertices[v]; Vector3 world = transform.TransformPoint(vert.position); Vector3 screen = camera.WorldToScreenPoint(world); if (screen.z > 0) { screen.z = 0; float mouseDist2 = Vector2.SqrMagnitude((Vector2)screen - mousePos); float camDist = Vector3.Distance(camera.transform.position, world) - bump * 3; if (mouseDist2 < radius * radius && camDist < minDist) { selVertex = v; minDist = camDist; } } } foreach (var e in GetEdges()) { Vertex vert1 = vertices[e.Item1]; Vertex vert2 = vertices[e.Item2]; Vector3 v1 = vert1.position; Vector3 v2 = vert2.position; Vector3 segment = v2 - v1; Vector3 c = Vector3.Cross(camera.transform.forward, segment); Vector3 n = Vector3.Cross(c, segment); Plane plane = new Plane(n, v1); float camDist; if (plane.Raycast(ray, out camDist) && camDist - bump < minDist) { Vector3 hitPos = ray.GetPoint(camDist); Vector3 hitProj = MathUtil.ProjectPointOnLineSegment(v1, v2, hitPos); Vector3 projScreen = camera.WorldToScreenPoint(transform.TransformPoint(hitProj)); if (projScreen.z > 0 && Vector2.Distance(projScreen, mousePos) < radius * 0.6f) { selEdge = e; selVertex = -1; minDist = camDist - bump; } } } for (int f = 0; f < faces.Count; f++) { Face face = faces[f]; Vector3 normal = face.GetNormal(this); Plane plane = new Plane(normal, vertices[face.vertices[0]].position); float dist; if (plane.Raycast(ray, out dist) && dist < minDist) { Vector3 hitPos = ray.GetPoint(dist); bool inside = true; for (int i = 0; i < face.vertices.Count; i++) { int j = (i + 1) % face.vertices.Count; Vector3 v1 = vertices[face.vertices[i]].position; Vector3 v2 = vertices[face.vertices[j]].position; Vector3 edge = v2 - v1; Vector3 toHit = hitPos - v1; Vector3 cross = Vector3.Cross(edge, toHit); if (Vector3.Dot(cross, normal) < 0) { inside = false; break; } } if (inside) { selVertex = -1; selEdge = new UnorderedPair <int>(-1, -1); selFace = f; minDist = dist; } } } }
/// <summary> /// Distance of a point to a bezier curve(given by the two end points and the two control points). /// </summary> /// <returns> /// Return the square of the distance,and also the closest point on bezier, and the t value coresponding to that closest point. /// </returns> public static float DistPointToBezier(Vector2 point, Vector2 p1, Vector2 c1, Vector2 c2, Vector2 p2, out Vector2 closestPoint, out float closestPointTValue) { //we're going to project the point on the bezier curve,so to know how close it is closestPoint = Vector2.zero; closestPointTValue = 0; Vector2 pointNorm = point; Vector2 p1Norm = p1; Vector2 c1Norm = c1; Vector2 c2Norm = c2; Vector2 p2Norm = p2; //move the whole bezier curve so that the mouse location si translated to the origin p1Norm -= pointNorm; c1Norm -= pointNorm; c2Norm -= pointNorm; p2Norm -= pointNorm; //here are the factors of B(t) Vector2 A = -p1Norm + 3.0F * c1Norm - 3.0F * c2Norm + p2Norm; Vector2 B = 3.0F * p1Norm - 6.0F * c1Norm + 3.0F * c2Norm; Vector2 C = -3.0F * p1Norm + 3.0F * c1Norm; Vector2 D = p1Norm; //calculates the factor of B(t)*B'(t)..this is a 5th degree polynom const int max_degree = 5; int degree = max_degree; //finds the real degree float[] Q = new float[max_degree + 1]; Q[0] = 3.0F * Vector2.Dot(A, A); Q[1] = (5.0F * Vector2.Dot(A, B)); Q[2] = (4.0F * Vector2.Dot(A, C) + 2.0F * Vector2.Dot(B, B)); Q[3] = (3.0F * Vector2.Dot(B, C) + 3.0F * Vector2.Dot(A, D)); Q[4] = (Vector2.Dot(C, C) + 2.0F * Vector2.Dot(B, D)); Q[5] = Vector2.Dot(C, D); const float error = 0.00001f; //accepted error for (int j = 0; j < max_degree; ++j) { //we should consider nil, the very small values if (System.Math.Abs(Q[j]) < error) { degree -= 1; } else { for (int k = j + 1; k < max_degree + 1; ++k) { Q[k] /= Q[j]; } break; } } //get now the 't' value which is real and between 0.0F and 1.0F(if more usefull 't' values, calculate for each one the coresponding point,so to find wich is the closest) //use Durand-Kerner method Vector2 complex = new Vector2(0.4f, 0.9f); //randomly chosen value Vector2[] t = new Vector2[degree]; for (int j = 0; j < degree; ++j) { t[j] = pow(complex, j); } Vector2[] t_prev = new Vector2[degree]; const int MAX_ITERS = 15; int count = 0; bool condition; do { condition = false; for (int j = 0; j < degree; ++j) { t_prev[j] = t[j]; Vector2 denom = Vector2.right; for (int k = 0; k < degree; ++k) { if (j != k) { denom = ComplexMultiplier(denom, t[j] - t[k]); } } Vector2 revDenom = new Vector2(denom.x, -denom.y) / denom.sqrMagnitude; t[j] = t[j] - ComplexMultiplier(f(t[j], Q, max_degree - degree), revDenom); } count += 1; for (int j = 0; j < degree; ++j) { condition = condition || (Mathf.Abs(t[j].y - t_prev[j].y) >= error || Mathf.Abs(t[j].x - t_prev[j].x) >= error); } }while ((count < MAX_ITERS) && condition); float distance = -1.0F; for (int j = 0; j < degree; ++j) { if (Mathf.Abs(t[j].y) < error && t[j].x >= 0.0F && t[j].x <= 1.0F) { Vector2 samplePoint = Curves.SampleBezier((float)t[j].x, p1, c1, c2, p2); float dist = Vector2.SqrMagnitude(samplePoint - point); if (distance < 0.0F || dist < distance) { distance = dist; //get the closest point that is on the curve (if any ..) closestPoint = samplePoint; closestPointTValue = (float)t[j].x; } } } if (distance < 0) { return(Mathf.Infinity); } return(distance); }
public void OnEndLineString() { if (polyline.Count < 2) { return; } float extrude = options.Width * 0.5f; float invWidth = 1.0f / options.Width; if (polyline.Count == 2) { // Trivial case, build a quad polygonBuilder.OnBeginPolygon(); polygonBuilder.OnBeginLinearRing(); var currPoint = polyline[0]; var nextPoint = polyline[1]; // Create a quad around the segment var n0 = Perp(nextPoint - currPoint) * extrude; polygonBuilder.OnPoint(new Point(currPoint.x - n0.x, currPoint.y - n0.y)); polygonBuilder.OnPoint(new Point(currPoint.x + n0.x, currPoint.y + n0.y)); polygonBuilder.OnPoint(new Point(nextPoint.x + n0.x, nextPoint.y + n0.y)); polygonBuilder.OnPoint(new Point(nextPoint.x - n0.x, nextPoint.y - n0.y)); // Close the polygon polygonBuilder.OnPoint(new Point(currPoint.x - n0.x, currPoint.y - n0.y)); AddUVs((nextPoint - currPoint).magnitude * invWidth); polygonBuilder.OnEndLinearRing(); polygonBuilder.OnEndPolygon(); } else { Vector2 currPoint, nextPoint, lastPoint, lastp0 = new Vector2(), lastp1 = new Vector2(); for (int i = 1; i < polyline.Count - 1; ++i) { polygonBuilder.OnBeginPolygon(); polygonBuilder.OnBeginLinearRing(); currPoint = polyline[i]; nextPoint = polyline[i + 1]; lastPoint = polyline[i - 1]; var n0 = Perp(currPoint - lastPoint) * extrude; var n1 = Perp(nextPoint - currPoint) * extrude; // First iteration, initialize lastp1 and lastp0 if (i == 1) { lastp1 = lastPoint - n0; lastp0 = lastPoint + n0; } Vector2 p0, p1; if (Vector2.SqrMagnitude(n0 - n1) < 0.0001f) { // Previous and current line vectors are collinear p0 = currPoint + n0; p1 = currPoint - n1; } else { // Right turn: Left turn: // n0 p0 p1 // ^ + + // | / nextPoint / // +---------+--> n1 +---------+ currPoint // lastPoint /| currPoint | p0 / | // p1 + | v + | // | n1 | // + n0 <--+ lastPoint // nextPoint // Define 2d cross product between v0(x0, y0) and v1(x1, y1) as: // v0 x v1 = v1.x * v0.y - v1.y * v0.x bool isRightTurn = n1.x * n0.y - n1.y * n0.x > 0.0f; Vector2 miter = Miter(lastPoint, currPoint, nextPoint, isRightTurn ? n0 : -n0, isRightTurn ? n1 : -n1); p0 = currPoint + miter * extrude; Vector2 intersection; bool intersect = Intersection(lastPoint, currPoint, nextPoint, isRightTurn ? -n0 : n0, isRightTurn ? -n1 : n1, out intersection); p1 = intersect ? intersection : currPoint + n0; if (!isRightTurn) { Util.Swap <Vector2>(ref p0, ref p1); } } polygonBuilder.OnPoint(new Point(lastp1.x, lastp1.y)); polygonBuilder.OnPoint(new Point(lastp0.x, lastp0.y)); polygonBuilder.OnPoint(new Point(p0.x, p0.y)); polygonBuilder.OnPoint(new Point(p1.x, p1.y)); // Close the polygon polygonBuilder.OnPoint(new Point(lastp1.x, lastp1.y)); lastp0 = p0; lastp1 = p1; AddUVs((currPoint - lastPoint).magnitude * invWidth); polygonBuilder.OnEndLinearRing(); polygonBuilder.OnEndPolygon(); // Last point, close the polyline if (i == polyline.Count - 2) { polygonBuilder.OnBeginPolygon(); polygonBuilder.OnBeginLinearRing(); polygonBuilder.OnPoint(new Point(lastp1.x, lastp1.y)); polygonBuilder.OnPoint(new Point(lastp0.x, lastp0.y)); polygonBuilder.OnPoint(new Point(nextPoint.x + n1.x, nextPoint.y + n1.y)); polygonBuilder.OnPoint(new Point(nextPoint.x - n1.x, nextPoint.y - n1.y)); // Close the polygon polygonBuilder.OnPoint(new Point(lastp1.x, lastp1.y)); AddUVs((nextPoint - currPoint).magnitude * invWidth); polygonBuilder.OnEndLinearRing(); polygonBuilder.OnEndPolygon(); } } } }
void FindThePath() { //if the player and the spider is at the same level if (distance_y <= 1) { //if player is on the left, same level with the spider if (distance_x < 0 && right) { //turn left move.x *= -1; //face left spriteRenderer.flipX = !spriteRenderer.flipX; //on the left right = false; } //if player is on the right, but spider is moving (facing) left else if (distance_x > 0 && !right) { //turn right move.x *= -1; //face right spriteRenderer.flipX = !spriteRenderer.flipX; //on the right right = true; } } //at different level else { //the best block to jump on GameObject best_block = null; //infinity float mini_distance = Mathf.Infinity; //spider's current position Vector2 spider_position = transform.position; //player's current position Vector2 player_position = target.transform.position; //The distance between the block and the spider (weight) Vector2 spider_block_vector; //The distance betweenn the block and the player (admissible heuristic) Vector2 player_block_vector; //higher? bool higher = false; if (player_position.y > spider_position.y) { higher = true; } //w + h float distance; foreach (GameObject o in objects) { spider_block_vector = new Vector2(o.transform.position.x - spider_position.x, o.transform.position.y - spider_position.y); player_block_vector = new Vector2(player_position.x - o.transform.position.x, player_position.y - o.transform.position.y); distance = spider_block_vector.SqrMagnitude() + player_position.SqrMagnitude(); if (distance < mini_distance && higher && o.transform.position.y > spider_position.y) { best_block = o; mini_distance = distance; } }//end foreach if (best_block.transform.position.x - spider_position.x < -2 && right)//6 { //turn left move.x *= -1; //face left spriteRenderer.flipX = !spriteRenderer.flipX; //on the left right = false; } else if (best_block.transform.position.x - spider_position.x > 2 && !right)//6 { //turn right move.x *= -1; //face right spriteRenderer.flipX = !spriteRenderer.flipX; //on the right right = true; } if (Mathf.Abs(best_block.transform.position.x - spider_position.x) < 2)//5 { velocity.y = jumpTakeOffSpeed; if (velocity.y > 0) { velocity.y = velocity.y * 0.5f; } } } //end else } //end FindThePath()
public void PlaceDoor(float x, float y) { Debug.Log("PlaceDoor"); Assets.Map.Center selectedCenter = Graph.centers.FirstOrDefault(p => p.PointInside(x, y)); if (selectedCenter == null) { Debug.Log("PlaceDoor: selectedCenter is null"); return; } // Generate List of edges which are valid for door placement. List <Assets.Map.Edge> validDoorEdges = new List <Assets.Map.Edge> (); for (int edgeIndex = 0; edgeIndex < selectedCenter.borders.Count; edgeIndex++) { Assets.Map.Edge selectedEdge = selectedCenter.borders[edgeIndex]; if (selectedEdge.v0 != null && selectedEdge.v1 != null) { if (Vector3.Magnitude(selectedEdge.v0.point - selectedEdge.v1.point) > 0) { validDoorEdges.Add(selectedEdge); } } } // remove existing door Viz game objects around selected center & store index of removed door Viz. int selectedEdgeIndex = 0; bool bRemovedDoor = false; for (int edgeIndex = 0; edgeIndex < validDoorEdges.Count; edgeIndex++) { Assets.Map.Edge selectedEdge = validDoorEdges[edgeIndex]; if (selectedEdge.gameObjectDoorViz.Count > 0) { selectedEdge.gameObjectDoorViz.ForEach(_gfx => Object.Destroy(_gfx)); selectedEdge.gameObjectDoorViz.Clear(); selectedEdgeIndex = edgeIndex; bRemovedDoor = true; } } // door placement will be at next edge index. if (bRemovedDoor == true) { selectedEdgeIndex++; } // this condition is used to define a state where no doors will be attached to the selected tile if (selectedEdgeIndex >= validDoorEdges.Count) { return; } Assets.Map.Edge edge = validDoorEdges[selectedEdgeIndex]; Assets.Map.Center adjCenter; // may be at either d0 or d1 if (edge.d0 == selectedCenter) // todo: floating point equaulity may break with non-integer floats. { adjCenter = edge.d1; } else { adjCenter = edge.d0; } int thisElevation = (int)selectedCenter.elevation; if (edge.v0 != null && edge.v1 != null) //graph border tiles may be null { //VIZ Vector3 newPos = (new Vector3(edge.v0.point.x, 0, edge.v0.point.y) + new Vector3(edge.v1.point.x, 0, edge.v1.point.y)) / 2; newPos.y = thisElevation; GameObject vizObj = Object.Instantiate(assetLibrary.GetComponent <AssetLibrary>().VizPrefabArch, newPos, Quaternion.identity) as GameObject; vizObj.name = "VizPrefabArch"; // flag MeshFilter game objects as viz layer MeshFilter[] childmf = vizObj.GetComponentsInChildren <MeshFilter>(); int ct = 0; while (ct < childmf.Length) { MeshFilter cmf = childmf[ct]; if (cmf != null) { cmf.gameObject.layer = 10; } ct++; } //rotate to angle of edge face float yAngle = Vector3.Angle(new Vector3(0, 0, 1), new Vector3(selectedCenter.point.x, 0, selectedCenter.point.y) - new Vector3(adjCenter.point.x, 0, adjCenter.point.y)); if (adjCenter.point.x > selectedCenter.point.x) { vizObj.transform.Rotate(0, -yAngle, 0); } else { vizObj.transform.Rotate(0, yAngle, 0); } Vector3 ls = vizObj.transform.localScale; ls.x = Mathf.Sqrt(Vector2.SqrMagnitude(edge.v0.point - edge.v1.point)); vizObj.transform.localScale = ls; vizObj.transform.SetParent(this.transform); edge.gameObjectDoorViz.Add(vizObj); } }
public static float v2sqd(Vector2 a, Vector2 b) { return(Vector2.SqrMagnitude(a - b)); }
private void BuildVoronoiTileGFX(Center c) { // Tiles c.gameObjectTile.ForEach(_gfx => Object.Destroy(_gfx)); if (c.elevation > 0) { Vector3 [] corners3d = c.corners.Select(p => new Vector3(p.point.x, 0.0f, p.point.y)).ToArray(); for (int crnIndex = 0; crnIndex < corners3d.Length; crnIndex++) { // Collision object { GameObject collisionObj = Object.Instantiate(assetLibrary.GetComponent <AssetLibrary>().collisionPrefab, new Vector3(c.point.x, 0, c.point.y), Quaternion.identity) as GameObject; collisionObj.layer = 8; //ground collisionObj.name = "groundCollision"; int startCrnIndex = crnIndex; int endCrnIndex = (crnIndex + 1) % corners3d.Length; Vector3[] vertices = new Vector3[] { new Vector3(0, c.elevation, 0), new Vector3(corners3d [startCrnIndex].x - c.point.x, c.elevation, corners3d [startCrnIndex].z - c.point.y), new Vector3(corners3d [endCrnIndex].x - c.point.x, c.elevation, corners3d [endCrnIndex].z - c.point.y) }; collisionObj.GetComponent <MeshFilter> ().mesh.name = "tileTri"; collisionObj.GetComponent <MeshFilter> ().mesh.vertices = vertices; collisionObj.GetComponent <MeshFilter> ().mesh.uv = new [] { new Vector2(0, 0), new Vector2(0, 1), new Vector2(1, 1) }; collisionObj.GetComponent <MeshFilter> ().mesh.triangles = new [] { 0, 1, 2, 0, 2, 0 }; collisionObj.GetComponent <MeshFilter> ().mesh.RecalculateNormals(); if (kbRenderCollisionMesh == true) { collisionObj.AddComponent <MeshRenderer>(); } collisionObj.transform.SetParent(this.transform); //collisionObj.AddComponent<MeshCollider>(); collisionObj.GetComponent <MeshCollider>().sharedMesh = collisionObj.GetComponent <MeshFilter>().mesh; c.gameObjectTile.Add(collisionObj); } //Viz object { GameObject vizObj = Object.Instantiate(assetLibrary.GetComponent <AssetLibrary>().VizPrefabGroundTile, new Vector3(c.point.x, 0, c.point.y), Quaternion.identity) as GameObject; vizObj.layer = 10; //viz vizObj.name = "groundViz"; int startCrnIndex = crnIndex; int endCrnIndex = (crnIndex + 1) % corners3d.Length; Vector3[] vertices = new Vector3[] { new Vector3(0, c.elevation, 0), new Vector3(corners3d [startCrnIndex].x - c.point.x, c.elevation, corners3d [startCrnIndex].z - c.point.y), new Vector3(corners3d [endCrnIndex].x - c.point.x, c.elevation, corners3d [endCrnIndex].z - c.point.y) }; vizObj.GetComponent <MeshFilter> ().mesh.name = "tileTri"; vizObj.GetComponent <MeshFilter> ().mesh.vertices = vertices; vizObj.GetComponent <MeshFilter> ().mesh.uv = new [] { new Vector2(0.366f, 0.460f), new Vector2(0.366f, 0.7f), new Vector2(0.568f, 0.7f) }; vizObj.GetComponent <MeshFilter> ().mesh.triangles = new [] { 0, 1, 2, 0, 2, 0 }; vizObj.GetComponent <MeshFilter> ().mesh.RecalculateNormals(); Material mat = Resources.Load("Materials/DungeonMat1", typeof(Material)) as Material; // i.e. .png, .jpg, etc Material [] mats = new Material[1]; mats [0] = mat; vizObj.transform.GetComponent <Renderer>().materials = mats; vizObj.transform.SetParent(this.transform); c.gameObjectTile.Add(vizObj); } } } // WALLS foreach (Assets.Map.Edge edge in c.borders) { edge.gameObjectWalls.ForEach(_gfx => Object.Destroy(_gfx)); edge.gameObjectWalls.Clear(); edge.gameObjectWallsViz.ForEach(_gfx => Object.Destroy(_gfx)); edge.gameObjectWallsViz.Clear(); // Remove edge ramps. edge.gameObjectRamp.ForEach(_gfx => Object.Destroy(_gfx)); edge.gameObjectRamp.Clear(); Assets.Map.Center adjCenter; // may be at either d0 or d1 if (edge.d0 == c) // todo: floating point equaulity may break with non-integer floats. { adjCenter = edge.d1; } else { adjCenter = edge.d0; } // place walls for all surrounding tiles which are of lower elevation // this ensures that walls are only generated once for adjacent tiles. if (c.elevation != adjCenter.elevation) { int lowerElevation = (int)Mathf.Min((int)adjCenter.elevation, (int)c.elevation); int higherElevation = (int)Mathf.Max((int)adjCenter.elevation, (int)c.elevation); for (int thisElevation = lowerElevation; thisElevation < higherElevation; thisElevation++) { if (edge.v0 != null && edge.v1 != null) //graph border tiles may be null { if (Vector3.Magnitude(edge.v0.point - edge.v1.point) > 0) { //VIZ Vector3 newPos = (new Vector3(edge.v0.point.x, 0, edge.v0.point.y) + new Vector3(edge.v1.point.x, 0, edge.v1.point.y)) / 2; newPos.y = thisElevation; GameObject vizObj = Object.Instantiate(assetLibrary.GetComponent <AssetLibrary>().VizPrefabWall, newPos, Quaternion.identity) as GameObject; vizObj.name = "VizPrefabWall"; // flag MeshFilter game objects as viz layer MeshFilter[] childmf = vizObj.GetComponentsInChildren <MeshFilter>(); int ct = 0; while (ct < childmf.Length) { MeshFilter cmf = childmf[ct]; if (cmf != null) { cmf.gameObject.layer = 10; } ct++; } //rotate to angle of edge face float yAngle = Vector3.Angle(new Vector3(0, 0, 1), new Vector3(c.point.x, 0, c.point.y) - new Vector3(adjCenter.point.x, 0, adjCenter.point.y)); if (adjCenter.point.x > c.point.x) { vizObj.transform.Rotate(0, -yAngle, 0); } else { vizObj.transform.Rotate(0, yAngle, 0); } Vector3 ls = vizObj.transform.localScale; ls.x = Mathf.Sqrt(Vector2.SqrMagnitude(edge.v0.point - edge.v1.point)); vizObj.transform.localScale = ls; vizObj.transform.SetParent(this.transform); edge.gameObjectWallsViz.Add(vizObj); // COLLISION GameObject collisionObj = Object.Instantiate(assetLibrary.GetComponent <AssetLibrary>().collisionPrefab, new Vector3(c.point.x, 0, c.point.y), Quaternion.identity) as GameObject; collisionObj.layer = 9; //obstacle collisionObj.name = "wallCollision"; if (kbRenderCollisionMesh == true) { collisionObj.AddComponent <MeshRenderer>(); } collisionObj.GetComponent <MeshFilter>().mesh.vertices = new Vector3[] { new Vector3(edge.v1.point.x - c.point.x, thisElevation + 1, edge.v1.point.y - c.point.y), new Vector3(edge.v1.point.x - c.point.x, thisElevation + 0, edge.v1.point.y - c.point.y), new Vector3(edge.v0.point.x - c.point.x, thisElevation + 1, edge.v0.point.y - c.point.y), new Vector3(edge.v0.point.x - c.point.x, thisElevation + 0, edge.v0.point.y - c.point.y), }; collisionObj.GetComponent <MeshFilter>().mesh.uv = new [] { new Vector2(1, 1), new Vector2(1, 0), new Vector2(0, 1), new Vector2(0, 0) }; // tri ordering is based on vectors between center and adjacent center if (c.point.y == adjCenter.point.y) //TODO: float equality { if (c.point.x > adjCenter.point.x) { if (c.elevation > adjCenter.elevation) { collisionObj.GetComponent <MeshFilter>().mesh.triangles = new [] { 0, 1, 2, 2, 1, 3 }; } else { collisionObj.GetComponent <MeshFilter>().mesh.triangles = new [] { 0, 2, 1, 1, 2, 3 }; } } else { if (c.elevation > adjCenter.elevation) { collisionObj.GetComponent <MeshFilter>().mesh.triangles = new [] { 0, 2, 1, 1, 2, 3 }; } else { collisionObj.GetComponent <MeshFilter>().mesh.triangles = new [] { 0, 1, 2, 2, 1, 3 }; } } } else if (c.point.y < adjCenter.point.y) { if (c.elevation > adjCenter.elevation) { collisionObj.GetComponent <MeshFilter>().mesh.triangles = new [] { 0, 2, 1, 1, 2, 3 }; } else { collisionObj.GetComponent <MeshFilter>().mesh.triangles = new [] { 0, 1, 2, 2, 1, 3 }; } } else if (c.point.y > adjCenter.point.y) { if (c.elevation > adjCenter.elevation) { collisionObj.GetComponent <MeshFilter>().mesh.triangles = new [] { 0, 1, 2, 2, 1, 3 }; } else { collisionObj.GetComponent <MeshFilter>().mesh.triangles = new [] { 0, 2, 1, 1, 2, 3 }; } } collisionObj.GetComponent <MeshFilter>().mesh.RecalculateNormals(); collisionObj.GetComponent <MeshCollider>().sharedMesh = collisionObj.GetComponent <MeshFilter>().mesh; collisionObj.transform.SetParent(this.transform); edge.gameObjectWalls.Add(collisionObj); } } } } } }
static float FaceRaycast(Vector3 mousePosition, ScenePickerPreferences pickerOptions, bool allowUnselected, SceneSelection selection, int deepClickOffset = 0, bool isPreview = true) { GameObject pickedGo = null; ProBuilderMesh pickedPb = null; Face pickedFace = null; int newHash = 0; // If any event modifiers are engaged don't cycle the deep click EventModifiers em = Event.current.modifiers; if (isPreview || em != EventModifiers.None) { EditorHandleUtility.GetHovered(mousePosition, s_OverlappingGameObjects); } else { EditorHandleUtility.GetAllOverlapping(mousePosition, s_OverlappingGameObjects); } selection.Clear(); float distance = Mathf.Infinity; for (int i = 0, next = 0, pickedCount = s_OverlappingGameObjects.Count; i < pickedCount; i++) { var go = s_OverlappingGameObjects[i]; var mesh = go.GetComponent <ProBuilderMesh>(); Face face = null; if (mesh != null && (allowUnselected || MeshSelection.topInternal.Contains(mesh))) { Ray ray = UHandleUtility.GUIPointToWorldRay(mousePosition); RaycastHit hit; if (UnityEngine.ProBuilder.HandleUtility.FaceRaycast(ray, mesh, out hit, Mathf.Infinity, pickerOptions.cullMode)) { face = mesh.facesInternal[hit.face]; distance = Vector2.SqrMagnitude(((Vector2)mousePosition) - HandleUtility.WorldToGUIPoint(mesh.transform.TransformPoint(hit.point))); } } // pb_Face doesn't define GetHashCode, meaning it falls to object.GetHashCode (reference comparison) int hash = face == null?go.GetHashCode() : face.GetHashCode(); if (s_DeepSelectionPrevious == hash) { next = (i + (1 + deepClickOffset)) % pickedCount; } if (next == i) { pickedGo = go; pickedPb = mesh; pickedFace = face; newHash = hash; // a prior hash was matched, this is the next. if // it's just the first iteration don't break (but do // set the default). if (next != 0) { break; } } } if (!isPreview) { s_DeepSelectionPrevious = newHash; } if (pickedGo != null) { Event.current.Use(); if (pickedPb != null) { if (pickedPb.selectable) { selection.gameObject = pickedGo; selection.mesh = pickedPb; selection.face = pickedFace; return(Mathf.Sqrt(distance)); } } // If clicked off a pb_Object but onto another gameobject, set the selection // and dip out. selection.gameObject = pickedGo; return(Mathf.Sqrt(distance)); } return(distance); }
private void Movement(Vector2 move, float time) { var maxSpeed = Input.GetButton("WalkMode") ? WalkSpeed : RunSpeed; speed = move.SqrMagnitude() > 0.1f ? Mathf.Clamp(speed + Acceleration * time, StartSpeed, maxSpeed) : Mathf.Clamp(speed - Acceleration * time, 0f, maxSpeed); var gravityDisplacement = Physics.gravity * time; playerController.Move(gravityDisplacement); if (UseShift) { var curCell = World.GetCell(transform.position); var cellDelta = curCell - lastCell; if (cellDelta.SqrMagnitude() > 0.1f) { Debug.Log("CELL SHIFT: " + cellDelta); var shift = new Vector3(World.CellSize.x * cellDelta.X, 0f, World.CellSize.y * cellDelta.Y); Debug.Log("SHIFT: " + shift); //StartCoroutine(World.ShiftRoutine(shift)); World.Shift(shift); curCell = World.GetCell(transform.position); } lastCell = curCell; } }
// Update is called once per frame void Update() { if (rayOn) { RaycastHit hit; Physics.Raycast(transform.position, transform.forward, out hit); if (Input.GetKeyDown(KeyCode.Tab)) Debug.Log("hi"); } int ret; float velocity_old = 0.0f; ret = wiiController.ReadWiimoteData(); wiiButton = wiiController.Button; if (ret > 0 && wiiButton.b) { oldVecz = newVecz; throwSet = true; Vector3 accel = GetAccelVector(); Vector3 accelNormal = accel; accelNormal.Normalize(); float sizeOfWidth = 2; leftRightMotion = accelNormal.x * (sizeOfWidth / 2); velocity_old = velocity; Vector2 vVec = new Vector2(accel.y, accel.z); velocity = Mathf.Sqrt(vVec.SqrMagnitude()); velocity *= Mathf.Sign(accel.y); velocity -= velocity_old; newVecz = leftRightMotion; if (finalVel <= velocity) { finalVel = velocity; fVelTime = Time.time; } iTween.ValueTo(gameObject, iTween.Hash("from", oldVecz, "to", newVecz, "time", Time.deltaTime, "onupdate", "ShowGhost")); } else if (!wiiButton.b && throwSet) { throwSet = false; Destroy(myBall); myBall = (GameObject)Instantiate(pingPong, new Vector3(transform.position.x - 1, transform.position.y, newVecz), Quaternion.identity); myBall.GetComponent<Rigidbody>().velocity = new Vector3(Mathf.Abs(finalVel) * -2, 2f, 0f); } if (Time.time - fVelTime > 1f) { finalVel = velocity; } if (Time.time - timeStart > 30f && playEnabled && false) { TimeUp(); } }
// Update is called once per frame void Update() { if (Application.platform == RuntimePlatform.Android || Application.platform == RuntimePlatform.IPhonePlayer || Application.platform == RuntimePlatform.MetroPlayerARM) { touchRay = Camera.main.ScreenPointToRay(Input.GetTouch(0).position); if (Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Began) { if (touchRay.origin.x >= -4.75f && touchRay.origin.x <= 4.75f && touchRay.origin.y >= -1.5f && touchRay.origin.y <= 3.5f) { m_PrevPos.x = touchRay.origin.x; m_PrevPos.y = touchRay.origin.y; // �P�_�ثeTP�Ҧb�� cloud float t = m_PrevPos.x * m_PrevPos.x + m_PrevPos.y * m_PrevPos.y; // cloud �����|�h(0,0)���ѦҤ��� �b�| 1.7 �� 2.5 ���ĥ|�h // 2.5 �� 2.9 ���ĤT�h 2.9 �� 3.5 ���ĤG�h, 3.5 ���~����1�h // (1.7^2 = 2.89, 2.5^2 = 6.25 2.9^2 = 8.41 3.5^2 = 12.25 ) if (t >= 2.89 && t < 6.25) m_iCloud = 4; else if (t >= 6.25 && t < 8.41) m_iCloud = 3; else if (t >= 8.41 && t < 12.25) m_iCloud = 2; else if (t >= 12.25) m_iCloud = 1; if (m_bAutoRotating) { // �I�s�|�� cloud ���L�̰������ m_Cloud1Script.Stop(); m_Cloud2Script.Stop(); m_Cloud3Script.Stop(); m_Cloud4Script.Stop(); m_CurrPos = m_PrevPos; } } } else if (Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Moved) { // �ھک즲�����f�ɤ�V�ӳ]�w��ʪ���V, �ھڲ��ʪ��t�Z�ӭp����ʪ����� if ( touchRay.origin.x >= -4.75f && touchRay.origin.x <= 4.75f && touchRay.origin.y >= -1.5f && touchRay.origin.y <= 3.5f) { m_CurrPos.x = touchRay.origin.x; m_CurrPos.y = touchRay.origin.y; float px, py, nx, ny, t; px = m_PrevPos.x - m_FWCenter.x; // ���ѽ����߫��V�e�@�� TP ���V�q py = m_PrevPos.y - m_FWCenter.y; nx = m_CurrPos.x - m_FWCenter.x; // ���ѽ����߫��V�ثe TP ���V�q ny = m_CurrPos.y - m_FWCenter.y; t = px * ny - py * nx; // (px,py) �P (nx, ny) ���~�n, > 0 �N��f�ɰw, < 0 �N����ɰw m_TPDelta = Input.GetTouch(0).deltaPosition; if (t >= 0) m_fdegree = -m_TPDelta.SqrMagnitude() * 1.5f; else m_fdegree = m_TPDelta.SqrMagnitude() * 1.5f; switch (m_iCloud) { case 1: m_Cloud1Script.RotateWithDegree(m_fdegree); m_Cloud2Script.RotateWithDiff(m_fdegree); m_Cloud3Script.RotateWithDiff(-m_fdegree); m_Cloud4Script.RotateWithDiff(-m_fdegree); break; case 2: m_Cloud1Script.RotateWithDiff(m_fdegree); m_Cloud2Script.RotateWithDegree(m_fdegree); m_Cloud3Script.RotateWithDiff(-m_fdegree); m_Cloud4Script.RotateWithDiff(-m_fdegree); break; case 3: m_Cloud1Script.RotateWithDiff(-m_fdegree); m_Cloud2Script.RotateWithDiff(-m_fdegree); m_Cloud3Script.RotateWithDegree(m_fdegree); m_Cloud4Script.RotateWithDiff(m_fdegree); break; case 4: m_Cloud1Script.RotateWithDiff(-m_fdegree); m_Cloud2Script.RotateWithDiff(-m_fdegree); m_Cloud3Script.RotateWithDiff(m_fdegree); m_Cloud4Script.RotateWithDegree(m_fdegree); break; } m_PrevPos = m_CurrPos; } } else if (Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Ended) { float px, py, nx, ny, t; Vector2 FinalVec; m_EndPos.x = touchRay.origin.x; m_EndPos.y = touchRay.origin.y; FinalVec = m_EndPos - m_CurrPos; float fdiff = FinalVec.SqrMagnitude(); // �P�_���ʪ��t�O�_�W�L�@�w�t��, ���|��cloud �۰ʱ��� if (fdiff > 0.25f ) { // �p��t�סA �����@�Ӳ��ʪ��q, �� Update �B��ۦ���� m_fSpeed = fdiff; px = m_CurrPos.x - m_FWCenter.x; // ���ѽ����߫��V�e�@�� TP ���V�q py = m_CurrPos.y - m_FWCenter.y; nx = m_EndPos.x - m_FWCenter.x; // ���ѽ����߫��V�ثe TP ���V�q ny = m_EndPos.y - m_FWCenter.y; t = px * ny - py * nx; // (px,py) �P (nx, ny) ���~�n, > 0 �N��f�ɰw, < 0 �N����ɰw if (t >= 0) m_fdegree = -m_fSpeed*1.25f; else m_fdegree = m_fSpeed * 1.25f; m_bAutoRotating = true; switch (m_iCloud) { case 1: m_Cloud1Script.AutoRotating(m_fdegree); m_Cloud2Script.AutoRotatingDiff(m_fdegree); m_Cloud3Script.AutoRotatingDiff(-m_fdegree); m_Cloud4Script.AutoRotatingDiff(-m_fdegree); break; case 2: m_Cloud1Script.AutoRotatingDiff(m_fdegree); m_Cloud2Script.AutoRotating(m_fdegree); m_Cloud3Script.AutoRotatingDiff(-m_fdegree); m_Cloud4Script.AutoRotatingDiff(-m_fdegree); break; case 3: m_Cloud1Script.AutoRotatingDiff(-m_fdegree); m_Cloud2Script.AutoRotatingDiff(-m_fdegree); m_Cloud3Script.AutoRotating(m_fdegree); m_Cloud4Script.AutoRotatingDiff(m_fdegree); break; case 4: m_Cloud1Script.AutoRotatingDiff(-m_fdegree); m_Cloud2Script.AutoRotatingDiff(-m_fdegree); m_Cloud3Script.AutoRotatingDiff(m_fdegree); m_Cloud4Script.AutoRotating(m_fdegree); break; } } } } }
void Update() { if (noControl) { return; } if (use_keyboard) { steering.x = Input.GetAxis("Horizontal"); steering.y = Input.GetAxis("Vertical"); } else { prevState = state; state = GamePad.GetState(playerIndex); if (thumbstick == Thumbstick.Left) { steering.x = state.ThumbSticks.Left.X; steering.y = state.ThumbSticks.Left.Y; } else { steering.x = state.ThumbSticks.Right.X; steering.y = state.ThumbSticks.Right.Y; } } float mag = Vector2.SqrMagnitude(steering); motorAudio.volume = Mathf.Clamp(mag, 0, 1); motorAudio.pitch = Mathf.Clamp(mag, 0.8f, 1f); bool noInput = steering == Vector2.zero; steering = steering.normalized; if (Mathf.Abs(steering.x) == 1) { steering.y += 0.01f; } Vector3 steering3 = Vector3.right * steering.x + Vector3.forward * steering.y; float forwardDot = Vector3.Dot(steering3, transform.forward); float dot = Vector3.Dot(steering3, transform.right); if (forwardDot < settings.reverseMaxDot) { steering3 += Mathf.Sign(dot) * transform.right * settings.reverseOffset; steering3 = steering3.normalized * mag; } dot = Vector3.Dot(steering3, transform.right); if (Mathf.Abs(dot) < settings.innerOuterDeadzone) { dot = 0; } int drivingDirection = 0; if (dot != 0) { drivingDirection = (int)Mathf.Sign(dot); } wheelsOffGround = 0; for (int i = 0; i < wheels.Length; i++) { bool wheelIsRight = i % 2 == 0; //ground check bool onGround = Physics.Raycast(wheels[i].transform.position, -transform.up, settings.onGroundCheckDistance); Debug.DrawRay(wheels[i].transform.position, -transform.up * settings.onGroundCheckDistance, Color.red); if (!onGround) { wheelsOffGround++; } if (noInput) { continue; } float dir = Vector3.Dot(wheels[i].transform.forward, steering3); if (i < 2) //assume first two wheels are front wheels and therefor rotate { wheels[i].transform.rotation = Quaternion.LookRotation(steering3, Vector3.right); dir = settings.frontWheelForce.Evaluate(dir); Debug.DrawRay(wheels[i].transform.position + 0.5f * Vector3.up, steering3.normalized, Color.green); } else { bool drivingBackwards = dir < 0; dir = settings.backWheelForce.Evaluate(dir); } if (!onGround) { continue; } Vector3 force = wheels[i].transform.forward * settings.moveForce * dir; Color c; if ((wheelIsRight && drivingDirection == 1) || (!wheelIsRight && drivingDirection == -1)) { force *= settings.wheelIsInnerForce; c = Color.blue; } else if ((wheelIsRight && drivingDirection == -1) || (!wheelIsRight && drivingDirection == 1)) { force *= settings.wheelIsOuterForce; c = Color.red; } else { force *= settings.wheelStraightForce; c = Color.magenta; } if (drivingDirection == -1) { force *= 1.1f; } Debug.DrawRay(wheels[i].transform.position, force.normalized, c); wheelForce[i] = force.magnitude; body.AddForceAtPosition(force * Time.deltaTime, wheels[i].transform.position); } float upDot = Vector3.Dot(transform.up, Vector3.up); if (upDot < 0.75 && wheelsOffGround > 1 && body.velocity.magnitude < settings.flipMinVelocity) { if (startFlipAction == -1) { startFlipAction = Time.time + settings.flipDelay; } if (startFlipAction < Time.time) { startFlipAction = -1; transform.rotation = Quaternion.Euler(0, 0, 0); transform.position += Vector3.up; } } else { startFlipAction = -1; } if (state.Buttons.Back == ButtonState.Pressed && prevState.Buttons.Back == ButtonState.Released) { if (nextFlipAllowed < Time.time) { nextFlipAllowed = Time.time + nextFlipDelay; transform.rotation = Quaternion.Euler(0, 0, 0); transform.position += Vector3.up; } } //Visual Wheels visuals[(int)roverType].UpdateWheels(wheels); }
private int GetClosestT(Vector2 point, ref float[] solutions) { int count = 0; Vector2 dxy = points[0] - point; Vector2 exy = points[0] - (2.0f * points[1]) + points[2]; Vector2 fxy = 2.0f * (points[1] - points[0]); float d = 2.0f * exy.SqrMagnitude(); float a, b, u, v, w, q, p, r, x; if (d == 0.0f) { b = fxy.SqrMagnitude() + 2.0f * Vector2.Dot(dxy, exy); if (b < 0.0f && -b < float.Epsilon) { return(count); } else if (b < float.Epsilon) { return(count); } solutions[count++] = -Vector2.Dot(fxy, dxy) / b; } else { float dInv = 1.0f / d; a = 3.0f * Vector2.Dot(fxy, exy) * dInv; b = (fxy.SqrMagnitude() + 2.0f * Vector2.Dot(dxy, exy)) * dInv; p = -a * a * ONE_THIRD + b; q = a * a * a * 0.074074074074074f - a * b * ONE_THIRD + Vector2.Dot(fxy, dxy) * dInv; r = q * q * 0.25f + p * p * p * 0.037037037037037f; if (r >= 0.0f) { r = Mathf.Sqrt(r); x = Sqrt3(-q * 0.5f + r) + Sqrt3(-q * 0.5f - r) - a * ONE_THIRD; } else { x = 2.0f * Mathf.Sqrt(-p * ONE_THIRD) * Mathf.Cos(Mathf.Atan2(Mathf.Sqrt(-r), -q * 0.5f) * ONE_THIRD) - a * ONE_THIRD; } u = x + a; v = x * x + a * x + b; w = u * u - 4.0f * v; if (w < 0.0f) { solutions[count++] = x; } else if (w > 0.0f) { w = Mathf.Sqrt(w); solutions[count++] = x; solutions[count++] = (-(u + w) * 0.5f); solutions[count++] = ((w - u) * 0.5f); } else { solutions[count++] = x; solutions[count++] = (-u * 0.5f); } } return(count); }
// Ramp between selectedCenter and target center (c) public void AddRamp(Assets.Map.Center selectedCenter, Assets.Map.Center c) { if (c.elevation < selectedCenter.elevation) { foreach (Assets.Map.Edge edge in c.borders) { if (edge.d0 == selectedCenter || edge.d1 == selectedCenter) // todo: floating point equaulity may break with non-integer floats. { // this is the edge which connects to the selected site if (edge.gameObjectRamp.Count == 0) { edge.gameObjectWalls.ForEach(_gfx => Object.Destroy(_gfx)); edge.gameObjectWalls.Clear(); edge.gameObjectWallsViz.ForEach(_gfx => Object.Destroy(_gfx)); edge.gameObjectWallsViz.Clear(); edge.gameObjectRamp.ForEach(_gfx => Object.Destroy(_gfx)); edge.gameObjectRamp.Clear(); Vector2 halfEdgeVector = edge.v0.point - edge.v1.point; halfEdgeVector = halfEdgeVector / 2; Vector2 centerVector = c.point - selectedCenter.point; centerVector = centerVector / 2; GameObject obj = Object.Instantiate(assetLibrary.GetComponent <AssetLibrary>().collisionPrefab, new Vector3(c.point.x, 0, c.point.y), Quaternion.identity) as GameObject; obj.layer = 8; //ground obj.name = "rampCollision"; //obj.GetComponent<Renderer>().enabled = false; // hide collison mesh obj.GetComponent <MeshFilter>().mesh.vertices = new Vector3[] { new Vector3(edge.v1.point.x - c.point.x, selectedCenter.elevation, edge.v1.point.y - c.point.y), new Vector3(edge.v1.point.x - c.point.x + centerVector.x, c.elevation, edge.v1.point.y - c.point.y + centerVector.y), new Vector3(edge.v0.point.x - c.point.x, selectedCenter.elevation, edge.v0.point.y - c.point.y), new Vector3(edge.v0.point.x - c.point.x + centerVector.x, c.elevation, edge.v0.point.y - c.point.y + centerVector.y) }; obj.GetComponent <MeshFilter>().mesh.uv = new [] { new Vector2(1, 1), new Vector2(1, 0), new Vector2(0, 1), new Vector2(0, 0) }; // tri ordering is based on vectors between center and adjacent center if (c.point.y == selectedCenter.point.y) //TODO: float equality { if (c.point.x < selectedCenter.point.x) { obj.GetComponent <MeshFilter>().mesh.triangles = new [] { 0, 1, 2, 2, 1, 3 }; } else { obj.GetComponent <MeshFilter>().mesh.triangles = new [] { 0, 2, 1, 1, 2, 3 }; } } else if (c.point.y > selectedCenter.point.y) { obj.GetComponent <MeshFilter>().mesh.triangles = new [] { 0, 2, 1, 1, 2, 3 }; } else if (c.point.y < selectedCenter.point.y) { obj.GetComponent <MeshFilter>().mesh.triangles = new [] { 0, 1, 2, 2, 1, 3 }; } obj.GetComponent <MeshFilter>().mesh.RecalculateNormals(); //obj.AddComponent<MeshCollider>(); obj.GetComponent <MeshCollider>().sharedMesh = obj.GetComponent <MeshFilter>().mesh; obj.transform.SetParent(this.transform); edge.gameObjectRamp.Add(obj); // Ramp Viz Object Vector3 newPos = (new Vector3(edge.v0.point.x, 0, edge.v0.point.y) + new Vector3(edge.v1.point.x, 0, edge.v1.point.y)) / 2; newPos.y = c.elevation; GameObject vizObj = Object.Instantiate(assetLibrary.GetComponent <AssetLibrary>().VizPrefabStair, newPos, Quaternion.identity) as GameObject; vizObj.name = "VizPrefabStair"; // flag MeshFilter game objects as viz layer MeshFilter[] childmf = vizObj.GetComponentsInChildren <MeshFilter>(); int ct = 0; while (ct < childmf.Length) { MeshFilter cmf = childmf[ct]; if (cmf != null) { cmf.gameObject.layer = 10; } ct++; } // rotate to angle of edge face float yAngle = Vector3.Angle(new Vector3(0, 0, 1), new Vector3(c.point.x, 0, c.point.y) - new Vector3(selectedCenter.point.x, 0, selectedCenter.point.y)); if (selectedCenter.point.x > c.point.x) { vizObj.transform.Rotate(0, -yAngle, 0); } else { vizObj.transform.Rotate(0, yAngle, 0); } Vector3 ls = vizObj.transform.localScale; ls.x = Mathf.Sqrt(Vector2.SqrMagnitude(edge.v0.point - edge.v1.point)) / 2.0f; ls.y = selectedCenter.elevation - c.elevation; vizObj.transform.localScale = ls; vizObj.transform.SetParent(this.transform); edge.gameObjectRamp.Add(vizObj); bRescanNavGraph = true; return; } } } } }
private void TryGetComponent(SelectType selectUsing, Vector2 screenPosition, ref Component component) { switch (selectUsing) { case SelectType.Raycast3D: { // Make sure the camera exists var camera = LeanTouch.GetCamera(Camera, gameObject); if (camera != null) { var ray = camera.ScreenPointToRay(screenPosition); var count = Physics.RaycastNonAlloc(ray, raycastHits, float.PositiveInfinity, LayerMask); if (count > 0) { component = raycastHits[GetClosestRaycastHitsIndex(count)].transform; } } else { Debug.LogError("Failed to find camera. Either tag your cameras MainCamera, or set one in this component.", this); } } break; case SelectType.Overlap2D: { // Make sure the camera exists var camera = LeanTouch.GetCamera(Camera, gameObject); if (camera != null) { var ray = camera.ScreenPointToRay(screenPosition); var count = Physics2D.GetRayIntersectionNonAlloc(ray, raycastHit2Ds, float.PositiveInfinity, LayerMask); if (count > 0) { component = raycastHit2Ds[0].transform; } } else { Debug.LogError("Failed to find camera. Either tag your cameras MainCamera, or set one in this component.", this); } } break; case SelectType.CanvasUI: { var results = LeanTouch.RaycastGui(screenPosition, LayerMask); if (results != null && results.Count > 0) { component = results[0].gameObject.transform; } } break; case SelectType.ScreenDistance: { var bestDistance = MaxScreenDistance * LeanTouch.ScalingFactor; bestDistance *= bestDistance; // Make sure the camera exists var camera = LeanTouch.GetCamera(Camera, gameObject); if (camera != null) { foreach (var selectable in LeanSelectable.Instances) { var distance = Vector2.SqrMagnitude(GetScreenPoint(camera, selectable.transform) - screenPosition); if (distance <= bestDistance) { bestDistance = distance; component = selectable; } } } } break; } }
/// <summary> /// Find points at which there are collisions with the geometry around a given point. /// </summary> /// <param name="geometryEdges">The boundary geometry.</param> /// <param name="point">The point around which collisions will be identified.</param> /// <param name="angleRadians">The angle, in radians, at which the collision points will be oriented.</param> /// <param name="topCollisionPoint">Receives the coordinates of the upper collision point.</param> /// <param name="bottomCollisionPoint">Receives the coordinates of the lower collision point.</param> /// <param name="leftCollisionPoint">Receives the coordinates of the left collision point.</param> /// <param name="rightCollisionPoint">Receives the coordinates of the right collision point.</param> /// <returns> /// True if all of the required collision points are located, false otherwise. /// If a point is unable to be found, the appropriate out parameter will be set to <see cref="EdgeUtilities.InvalidPoint"/>. /// </returns> private static bool FindSurroundingCollisionPoints( Edge[] geometryEdges, Vector2 point, float angleRadians, out Vector2 topCollisionPoint, out Vector2 bottomCollisionPoint, out Vector2 leftCollisionPoint, out Vector2 rightCollisionPoint) { // Initialize out parameters. topCollisionPoint = EdgeUtilities.InvalidPoint; bottomCollisionPoint = EdgeUtilities.InvalidPoint; leftCollisionPoint = EdgeUtilities.InvalidPoint; rightCollisionPoint = EdgeUtilities.InvalidPoint; // Check to see if the point is inside the geometry. if (!EdgeUtilities.IsInsideBoundary(geometryEdges, point)) { return(false); } // Define values that are outside of the maximum boundary size. float largeValue = EdgeUtilities.MaxWidth; float smallValue = -largeValue; // Find the top and bottom collision points by creating a large line segment that goes through the point to MAX and MIN values on Y var topEndpoint = new Vector2(point.x, largeValue); var bottomEndpoint = new Vector2(point.x, smallValue); topEndpoint = topEndpoint.RotateAroundPoint(point, angleRadians); bottomEndpoint = bottomEndpoint.RotateAroundPoint(point, angleRadians); var verticalLine = new Edge(topEndpoint, bottomEndpoint); // Find the left and right collision points by creating a large line segment that goes through the point to MAX and Min values on X var rightEndpoint = new Vector2(largeValue, point.y); var leftEndpoint = new Vector2(smallValue, point.y); rightEndpoint = rightEndpoint.RotateAroundPoint(point, angleRadians); leftEndpoint = leftEndpoint.RotateAroundPoint(point, angleRadians); var horizontalLine = new Edge(rightEndpoint, leftEndpoint); for (int i = 0; i < geometryEdges.Length; i++) { // Look for a vertical collision var verticalIntersectionPoint = EdgeUtilities.GetIntersectionPoint(geometryEdges[i], verticalLine); if (EdgeUtilities.IsValidPoint(verticalIntersectionPoint)) { // Is the intersection above or below the point? if (verticalIntersectionPoint.RotateAroundPoint(point, -angleRadians).y > point.y) { // Update the top collision point if (!EdgeUtilities.IsValidPoint(topCollisionPoint) || (Vector2.SqrMagnitude(point - verticalIntersectionPoint) < Vector2.SqrMagnitude(point - topCollisionPoint))) { topCollisionPoint = verticalIntersectionPoint; } } else { // Update the bottom collision point if (!EdgeUtilities.IsValidPoint(bottomCollisionPoint) || Vector2.SqrMagnitude(point - verticalIntersectionPoint) < Vector2.SqrMagnitude(point - bottomCollisionPoint)) { bottomCollisionPoint = verticalIntersectionPoint; } } } // Look for a horizontal collision var horizontalIntersection = EdgeUtilities.GetIntersectionPoint(geometryEdges[i], horizontalLine); if (!EdgeUtilities.IsValidPoint(horizontalIntersection)) { continue; } // Is this intersection to the left or the right of the point? if (horizontalIntersection.RotateAroundPoint(point, -angleRadians).x < point.x) { // Update the left collision point if (!EdgeUtilities.IsValidPoint(leftCollisionPoint) || (Vector2.SqrMagnitude(point - horizontalIntersection) < Vector2.SqrMagnitude(point - leftCollisionPoint))) { leftCollisionPoint = horizontalIntersection; } } else { // Update the right collision point if (!EdgeUtilities.IsValidPoint(rightCollisionPoint) || (Vector2.SqrMagnitude(point - horizontalIntersection) < Vector2.SqrMagnitude(point - rightCollisionPoint))) { rightCollisionPoint = horizontalIntersection; } } } // Each corner of the rectangle must intersect with the geometry. return(EdgeUtilities.IsValidPoint(topCollisionPoint) && EdgeUtilities.IsValidPoint(leftCollisionPoint) && EdgeUtilities.IsValidPoint(rightCollisionPoint) && EdgeUtilities.IsValidPoint(bottomCollisionPoint)); }
private float GetAreaOfRectangle(Vector2 a, Vector2 b, Vector2 c) => Mathf.Sqrt(Vector2.SqrMagnitude(a - b) * Vector2.SqrMagnitude(b - c));
new void Update() { base.Update(); if (checkIfDead && targetUnit == null) { bombsLeft = 0; ResetKeepTarget(); ResetLockOn(); } // Already dropping bombs onto a locked-on target if (bombsLeft > 0) { timeUntilNextBomb -= Time.deltaTime; if (timeUntilNextBomb <= 0) { timeUntilNextBomb = gameRules.ABLY_bombsDropTime / gameRules.ABLY_bombsCount; DetonateBomb(); } } else if (stacks > 0) // Not currently dropping bombs { // Lose lock over time if (keepTargetRemaining > 0 && lockOnRemaining > 0) { keepTargetRemaining -= Time.deltaTime; if (keepTargetRemaining <= 0) { ResetKeepTarget(); ResetLockOn(); } } // Lean based on velocity lockRayPosition.transform.forward = Vector3.down + leanMult * parentUnit.transform.forward * parentUnit.GetMovement().GetHVelocity().magnitude / parentUnitMS; // Lock on behaviour int raysConnected = 0; if (offCooldown && lockOnRemaining > 0) { Unit newTargetUnit = null; for (int i = 0; i < 5; i++) { // Raycast connects, too far from parent unit, or out of lifetime Vector3 noAngle = lockRayPosition.forward; Vector3 newVector = new Vector3(); if (i == 0) { newVector = noAngle; } else if (i == 1) { newVector = Quaternion.AngleAxis(0 + 45, -lockRayPosition.forward) * Quaternion.AngleAxis(lockRayAngle, lockRayPosition.up) * noAngle; } else if (i == 2) { newVector = Quaternion.AngleAxis(90 + 45, -lockRayPosition.forward) * Quaternion.AngleAxis(lockRayAngle, lockRayPosition.up) * noAngle; } else if (i == 3) { newVector = Quaternion.AngleAxis(180 + 45, -lockRayPosition.forward) * Quaternion.AngleAxis(lockRayAngle, lockRayPosition.up) * noAngle; } else if (i == 4) { newVector = Quaternion.AngleAxis(270 + 45, -lockRayPosition.forward) * Quaternion.AngleAxis(lockRayAngle, lockRayPosition.up) * noAngle; } RaycastHit hit; Ray rayCharles = new Ray(lockRayPosition.position, newVector); if (parentUnit.printInfo) { Debug.DrawLine(rayCharles.origin, rayCharles.origin + rayCharles.direction * lockRayDistance, Color.red); } //bool hitSelf = false; if (Physics.Raycast(rayCharles, out hit, lockRayDistance, mask)) { Unit unit = null; if (hit.collider.transform.parent) // Is this a unit? { unit = hit.collider.transform.parent.GetComponent <Unit>(); if (unit) // Is this a unit? { if (unit != parentUnit && unit.Team != team) // If we hit a unit and its not us, damage it { if (newTargetUnit == null) { newTargetUnit = unit; if (i == 0) { raysConnected += 10; } else { raysConnected++; } } else { if (unit == newTargetUnit) { if (i == 0) { raysConnected += 10; } else { raysConnected++; } } else if (parentUnit.printInfo) { Debug.Log(i + " not target unit"); } // else doesn't matter } } else if (parentUnit.printInfo) { Debug.Log(i + " its us or its an ally"); } } // if unit else if (parentUnit.printInfo) { Debug.Log(i + " not a unit"); } } // if has parent else if (parentUnit.printInfo) { Debug.Log(i + " no parent"); } } // if raycast else if (parentUnit.printInfo) { Debug.Log(i + " missed ray"); } } // for //if (newTargetUnit != null) SetTargetUnit(newTargetUnit); if (parentUnit.printInfo) { Debug.Log(raysConnected); } // At least 1 ray have to connect for lock-on to continue if (raysConnected >= 1) { lockOnRemaining -= Time.deltaTime; } else { ResetLockOn(); } // Locking on if (lockOnRemaining < gameRules.ABLY_bombsLockOnTime) { if (!lockOnSound.isPlaying) { lockOnSound.Play(); } if (lockOnRemaining < 0) { SucceedLockOn(); } } } // if missileActive Unit flagship = gameManager.GetCommander(team).GetFlagship(); if (stacks < gameRules.ABLY_bombsMaxAmmo && flagship) { // Missing ammo and near enough to flagship float distSqr = Vector2.SqrMagnitude(new Vector2(flagship.transform.position.x, flagship.transform.position.z) - new Vector2(transform.position.x, transform.position.z)); Debug.Log(Mathf.Sqrt(distSqr)); if (distSqr < gameRules.ABLY_bombsAmmoTickRange * gameRules.ABLY_bombsAmmoTickRange) { reloadTimer += deltaDurations.y * Time.deltaTime; DisplayFill(reloadTimer); if (reloadTimer >= 1) { stacks++; DisplayStacks(); reloadTimer = 0; } } else { reloadTimer = 0; } } } // bombsLeft <= 0 }
private Vector2 drawOrbitRadiusHelper(Vector2 eccentricity, double globalRotationAngle, double semiMajorAxis, double angle) { double radius = (semiMajorAxis * (1 - Vector2.SqrMagnitude(eccentricity))) / (1 - eccentricity.magnitude * (Math.Cos(angle - globalRotationAngle + Math.PI))); return(new Vector2((float)Math.Cos(angle), (float)Math.Sin(angle)) * (float)radius); }
public float ClosestPointParam(Vector2 pt) { Vector2 tmp = p1 - p0; return(Vector2.Dot(pt - p0, tmp) / tmp.SqrMagnitude()); }
/// <summary> /// MeshEdit중 "이전 위치 > 마우스 위치"로의 임시 Edge를 생성하여 GUI에 반영할 수 있도록 하는 함수. /// 교차 처리도 여기서 한다. /// Shift를 누르면 교차 처리가 Vertex 생성으로 이루어지므로 여러개의 교차점을 다른 색으로 표시한다. /// </summary> /// <param name="mousePos"></param> /// <param name="isShift"></param> public void UpdateEdgeWire(Vector2 mousePos, bool isShift) { if (!_isTmpEdgeWire || Vector2.SqrMagnitude(_tmpEdgeWire_MousePos - mousePos) > 1.0f) { //처음 Update를 하거나 마우스가 움직였을때 체크 if (_curVertex == null) { _isTmpEdgeWireCrossEdge = false; if (_isTmpEdgeWireCrossEdge_Multiple) { _tmpEdgeWireMultipleCrossPoints.Clear(); } _isTmpEdgeWireCrossEdge_Multiple = false; } else if (_mesh != null) { Vector2 mousePosW = apGL.GL2World(mousePos); Vector2 mousePosLocal2 = _mesh.Matrix_VertToLocal.inverse.MultiplyPoint(mousePosW); if (isShift) { //Shift가 눌리면 여러개의 VertexPos를 가져와야 한다. _isTmpEdgeWireCrossEdge = false; _tmpEdgeWireCrossPoint = Vector2.zero; _isTmpEdgeWireCrossEdge_Multiple = true; //_tmpEdgeWireMultipleCrossPoints.Clear(); IsAnyCrossEdgeMultiple(_curVertex, null, mousePosLocal2); if (_tmpEdgeWireMultipleCrossPoints.Count == 0) { _isTmpEdgeWireCrossEdge_Multiple = false; } } else { if (_isTmpEdgeWireCrossEdge_Multiple) { _tmpEdgeWireMultipleCrossPoints.Clear(); } _isTmpEdgeWireCrossEdge_Multiple = false; _isTmpEdgeWireCrossEdge = IsAnyCrossEdge(_curVertex, null, mousePosLocal2); if (_isTmpEdgeWireCrossEdge) { _tmpEdgeWireCrossPoint = _crossPoint._pos; //시작점이나 끝점에 가까우면 무시한다. if (Vector2.Distance(_curVertex._pos, _tmpEdgeWireCrossPoint) < 4.0f || Vector2.Distance(mousePosLocal2, _tmpEdgeWireCrossPoint) < 4.0f) { _isTmpEdgeWireCrossEdge = false; _tmpEdgeWireCrossPoint = Vector2.zero; } } } } } _isTmpEdgeWire = true; _tmpEdgeWire_MousePos = mousePos; }
List <StreetLineIntersectionResult> GetIntersectWithStreetLineResults(Vector2 start, Vector2 end, List <StreetLine> options, StreetLine ignored) { List <StreetLineIntersectionResult> intersectionResults = new List <StreetLineIntersectionResult>(); Vector2 intersection; for (int i = 0; i < options.Count; i++) { if (ignored != null && ignored == options[i]) { continue; } if (GeoMath.LineSegmentsIntersect(start, end, options[i].A, options[i].B, out intersection)) { intersectionResults.Add(new StreetLineIntersectionResult(options[i], intersection)); } } intersectionResults.Sort((a, b) => (Vector2.SqrMagnitude(start - a.intersection) < Vector2.SqrMagnitude(start - b.intersection)) ? -1 : 1); return(intersectionResults); }
// Update is called once per frame void Update() { // Missile state flow: switch (missileState) { case MissileState.disarmed: missile.radar.SetRadarOn(); if (debug) { statusText.text = "DA"; } missile.ThrustForward(1f); // to clear the player SQRdistanceToOwner = Vector2.SqrMagnitude(gameObject.transform.position - parentShip.position); if (SQRdistanceToOwner > armingSQRDistance) { stateChanging = true; if (!targetObject) { if (intendedState == MissileState.locked) { missileState = MissileState.scouting; } else { missileState = intendedState; } gameObject.GetComponent <BoxCollider2D>().enabled = true; } else { // InitialLockedManeuver(); missileState = MissileState.locked; gameObject.GetComponent <BoxCollider2D>().enabled = true; } } break; case MissileState.locked: if (debug) { statusText.text = "LCK"; } if (stateChanging) { AudioSource.PlayClipAtPoint(missileArmed, gameObject.transform.position, 0.8f); stateChanging = false; } Pursue(); break; case MissileState.scouting: if (debug) { statusText.text = "SCT"; } if (stateChanging) { AudioSource.PlayClipAtPoint(missileArmed, gameObject.transform.position, 0.8f); gameObject.GetComponent <BoxCollider2D>().enabled = true; stateChanging = false; } Scout(); break; case MissileState.mine: if (debug) { statusText.text = "MN"; } Loiter(); break; } if (missile.fuel < 0 && targetObject == null) { missile.SelfDestruct(); } if (debug) { statusText.text = statusText.text + " R: " + missile.radar.radarState + " F: " + missile.fuel; } }
//calculate the magnitude of the distance to find their similarity. 0 being perfect //used to provide a margin of wiggle room for the patrolling enemies public bool VecEqual(Vector2 a, Vector2 b) { return(Vector2.SqrMagnitude(a - b) < .00001); }
// Update is called once per frame void Update() { AnimatorStateInfo playerAnimatorState = playerAnimator.GetCurrentAnimatorStateInfo(0); // only one layer (0) // cast a ray downward, looking for only GroundLayer objects -> ("1 << " is unknown to me, but it's the way to do it, it seems) RaycastHit2D raycastInfo = Physics2D.Raycast(new Vector2(this.transform.position.x, this.transform.position.y - (colliderExtents.y + .005f)), -Vector2.up, Mathf.Infinity, 1 << LayerMask.NameToLayer("GroundLayer")); if (raycastInfo) { Debug.DrawLine(new Vector2(this.transform.position.x, this.transform.position.y - (colliderExtents.y + .005f)), raycastInfo.point, Color.red); } if ((!Input.GetKey(KeyCode.LeftShift) && playerNum == 1) || (!Input.GetKey(KeyCode.RightControl) && playerNum == 2)) // no GrappleActivator active { if (this.ActiveGrapple) // de-activate grapple { this.ActiveGrapple = false; this.rigidbody2D.gravityScale = 1; this.transform.eulerAngles = new Vector3(0, 0, 0); } if (Input.GetAxis("Horizontal" + playerNum) < 0) // run left { if (!playerAnimatorState.IsName("Run") || this.transform.localScale.x > 0) { this.transform.localScale = new Vector3(-transform.localScale.x, transform.localScale.y, transform.localScale.z); playerAnimator.Play("Run"); } this.transform.rigidbody2D.AddForce(new Vector2(-PlayerMoveForce, 0)); } else if (Input.GetAxis("Horizontal" + playerNum) > 0) { if (!playerAnimatorState.IsName("Run") || this.transform.localScale.x < 0) { this.transform.localScale = new Vector3(-transform.localScale.x, transform.localScale.y, transform.localScale.z); playerAnimator.Play("Run"); } this.transform.rigidbody2D.AddForce(new Vector2(PlayerMoveForce, 0)); } else if (!playerAnimatorState.IsName("Idle")) { playerAnimator.Play("Idle"); } float toRayPointSqrDistance = Vector2.SqrMagnitude(raycastInfo.point - new Vector2(this.transform.position.x, this.transform.position.y)); float distToSqrGround = (colliderExtents.y + GroundDisplace) * (colliderExtents.y + GroundDisplace); // make sure only jump when grounded if ((toRayPointSqrDistance < distToSqrGround) && Input.GetAxis("Jump" + playerNum) > 0) { this.transform.rigidbody2D.AddForce(new Vector2(0, PlayerJumpForce)); } // limit speed to the PlayerMaxSpeed if (this.transform.rigidbody2D.velocity.sqrMagnitude > PlayerMaxSpeed * PlayerMaxSpeed) { this.transform.rigidbody2D.velocity = this.transform.rigidbody2D.velocity.normalized * PlayerMaxSpeed; } } else // in grapple mode { //if (Input.GetAxis("GrappleActivator" + playerNum) > 0) //{ if (!playerAnimatorState.IsName("Idle")) { playerAnimator.Play("Idle"); } if (Input.GetAxis("Horizontal" + playerNum) < 0) { grappleDirection = -this.transform.right; } else if (Input.GetAxis("Horizontal" + playerNum) > 0) { grappleDirection = this.transform.right; } else if (Input.GetAxis("Vertical" + playerNum) < 0) { grappleDirection = -Vector2.up; } else if (Input.GetAxis("Vertical" + playerNum) > 0) { grappleDirection = Vector2.up; } this.transform.eulerAngles = new Vector3(0, 0, 0); currentGrappleTo = CalculateGrapple(grappleDirection); //} } if (this.ActiveGrapple) { if (this.rigidbody2D.gravityScale != 0) { this.rigidbody2D.gravityScale = 0; } this.rigidbody2D.velocity = MainPlayerShip.rigidbody2D.velocity; Vector2 pos = new Vector2(this.transform.position.x, this.transform.position.y); if ((currentGrappleTo.point - pos).sqrMagnitude >= GrappleStopDistance) { Vector2 direction = currentGrappleTo.point - pos; direction.Normalize(); this.transform.position = pos + direction * GrappleSpeed * Time.deltaTime; } } }
private void FixedUpdate() { if (movingPlayer) { Vector2 direction2D; Animator animator; for (int i = 0; i < playersNumber; i++) { if (players[i] != null) { if (!checkpointReached[i]) { if (players[i] == myPlayer) { Vector3 directionToCheckpoint = (positionCheckpoints[i].transform.position - players[i].transform.position).normalized; direction2D = new Vector2(directionToCheckpoint.x, directionToCheckpoint.y); players[i].GetComponent <PlayerControllerMap>().Move(directionToCheckpoint); animator = players[i].GetComponent <Animator>(); animator.SetFloat("Speed", direction2D.SqrMagnitude()); animator.SetFloat("Horizontal", direction2D.x); } } } else { checkpointReached[i] = true; } } if (checkpointReached.All(x => x)) { if (!finalBoss) { direction2D = Vector2.up; myPlayer.GetComponent <PlayerControllerMap>().Move(Vector3.up); Debug.Log(myPlayer); Debug.Log(myPlayer.GetComponent <PhotonView>().ViewID); animator = myPlayer.GetComponent <Animator>(); animator.SetFloat("Speed", direction2D.SqrMagnitude()); animator.SetFloat("Horizontal", direction2D.x); if (myPlayer.transform.position.y >= finalPosition.position.y) { finalBoss = true; } } else { if (!finalCheckpointReached.All(x => x)) { for (int i = 0; i < playersNumber; i++) { if (players[i] != null) { if (Vector3.Distance(players[i].transform.position, finalCheckpoints[i].transform.position) > 0.1f && !finalCheckpointReached[i]) { if (players[i] == myPlayer) { Vector3 directionToCheckpoint = (finalCheckpoints[i].transform.position - players[i].transform.position).normalized; direction2D = new Vector2(directionToCheckpoint.x, directionToCheckpoint.y); players[i].GetComponent <PlayerControllerMap>().Move(directionToCheckpoint); animator = players[i].GetComponent <Animator>(); animator.SetFloat("Speed", direction2D.SqrMagnitude()); animator.SetFloat("Horizontal", direction2D.x); } } else { finalCheckpointReached[i] = true; if (players[i] == myPlayer) { animator = players[i].GetComponent <Animator>(); animator.SetFloat("Speed", 0); animator.SetFloat("Horizontal", (boss.transform.position - players[i].transform.position).x); } } } } } if (!setUpFinal) { boss.ActivateAnimator(this); myPlayer.GetComponent <PlayerControllerMap>().SetTimer(999, true); endgameVCAM.gameObject.SetActive(true); setUpFinal = true; } if (isBossExploded) { direction2D = Vector2.up; myPlayer.GetComponent <PlayerControllerMap>().SetTimer(0, false); myPlayer.GetComponent <PlayerControllerMap>().Move(Vector3.up); animator = myPlayer.GetComponent <Animator>(); animator.SetFloat("Speed", direction2D.SqrMagnitude()); animator.SetFloat("Horizontal", direction2D.x); } } } } }
private bool GroupedFingers() { return(Vector2.SqrMagnitude(Input.GetTouch(0).deltaPosition) > 10f && Vector2.SqrMagnitude(Input.GetTouch(1).deltaPosition) > 10 && Vector2.Angle(Input.GetTouch(0).deltaPosition, Input.GetTouch(1).deltaPosition) < 90); }
public void OnLocalGUI(Rect r) { //r = r.PadTop(Mathf.CeilToInt(22*zoom)); editor.mousePosition = Event.current.mousePosition; rect = r; // TOOLBAR //DrawToolbar( new Rect( rect.x, rect.y, rect.width, TOOLBAR_HEIGHT ) ); Rect localRect = new Rect(r); localRect.x = 0; localRect.y = 0; //rect.y += TOOLBAR_HEIGHT; //rect.height -= TOOLBAR_HEIGHT; // VIEW Rect rectInner = new Rect(rect); rectInner.width = float.MaxValue / 2f; rectInner.height = float.MaxValue / 2f; // TEMP: // Rect btn = rectInner; // btn.width = 64; // btn.height = 24; // if(SF_Debug.renderDataNodes){ // if(selection.Selection.Count > 0){ // if(GUI.Button(btn,"NSS")){ // editor.TakeNodePreviewScreenshot(); // } // } // } if (Event.current.type == EventType.Repaint) { nodeSpaceMousePos = ScreenSpaceToZoomSpace(Event.current.mousePosition); } bool mouseOverNode = false; SF_ZoomArea.Begin(zoom, rect, cameraPos); { selection.OnGUI(); // To detect if you press things if (editor.nodeView != null) { editor.nodeView.selection.DrawBoxSelection(); } if (Event.current.type == EventType.Repaint) { viewSpaceMousePos = ZoomSpaceToScreenSpace(Event.current.mousePosition); } // NODES if (editor.nodes != null) { // If we're repainting, draw in reverse to sort properly //if(Event.current.rawType == EventType.repaint){ for (int i = editor.nodes.Count - 1; i >= 0; i--) { if (!editor.nodes[i].Draw()) { break; } } /*} else { * for(int i=0;i<editor.nodes.Count;i++) { * if( !editor.nodes[i].Draw() ) * break; * } * }*/ if (!mouseOverNode) { for (int i = 0; i < editor.nodes.Count; i++) { if (editor.nodes[i].MouseOverNode(world: true)) { mouseOverNode = true; } } } if (Event.current.type == EventType.Repaint) { for (int i = 0; i < editor.nodes.Count; i++) { editor.nodes[i].DrawConnectors(); } } } UpdateCutLine(); UpdateCameraPanning(); } SF_ZoomArea.End(zoom); if (!SF_Node.isEditingAnyNodeTextField) { SF_Editor.instance.UpdateKeyHoldEvents(mouseOverNode); } if (MouseInsideNodeView(false) && Event.current.type == EventType.ScrollWheel) { zoomTarget = ClampZoom(zoomTarget * (1f - Event.current.delta.y * 0.02f)); } SetZoom(Mathf.Lerp(zoom, zoomTarget, 0.2f)); if (Event.current.type == EventType.ContextClick && !SF_GUI.HoldingAlt()) { Vector2 mousePos = Event.current.mousePosition; if (rect.Contains(mousePos)) { // Now create the menu, add items and show it GenericMenu menu = new GenericMenu(); // First item is for creating a comment box //menu.AddItem( new GUIContent("Create comment box"), false, ContextClick, mousePos ); //menu.AddSeparator(""); for (int i = 0; i < editor.nodeTemplates.Count; i++) { if (editor.ps.catLighting.renderPath == SFPSC_Lighting.RenderPath.Deferred && !editor.nodeTemplates[i].availableInDeferredPrePass) { continue; // Skip forward nodes when in deferred } menu.AddItem(new GUIContent(editor.nodeTemplates[i].fullPath), false, ContextClick, editor.nodeTemplates[i]); } editor.ResetRunningOutdatedTimer(); menu.ShowAsContext(); Event.current.Use(); } } if (Event.current.type == EventType.DragPerform) { Object droppedObj = DragAndDrop.objectReferences[0]; if (droppedObj is Texture2D || /*droppedObj is ProceduralTexture ||*/ droppedObj is RenderTexture) { SFN_Tex2d texNode = editor.nodeBrowser.OnStopDrag() as SFN_Tex2d; texNode.TextureAsset = droppedObj as Texture; texNode.OnAssignedTexture(); Event.current.Use(); } //if(droppedObj is ProceduralMaterial){ // OnDroppedSubstance(droppedObj as ProceduralMaterial); //} } if (Event.current.type == EventType.DragUpdated && Event.current.type != EventType.DragPerform) { if (DragAndDrop.objectReferences.Length > 0) { Object dragObj = DragAndDrop.objectReferences[0]; if (dragObj is Texture2D || /*dragObj is ProceduralTexture || */ dragObj is RenderTexture) { DragAndDrop.visualMode = DragAndDropVisualMode.Link; if (!editor.nodeBrowser.IsPlacing()) { editor.nodeBrowser.OnStartDrag(editor.GetTemplate <SFN_Tex2d>()); } else { editor.nodeBrowser.UpdateDrag(); } } // else if(dragObj is ProceduralMaterial){ // DragAndDrop.visualMode = DragAndDropVisualMode.Link; //} else { DragAndDrop.visualMode = DragAndDropVisualMode.Rejected; } } else { DragAndDrop.visualMode = DragAndDropVisualMode.Rejected; } } // If release if (MouseInsideNodeView(false) && Event.current.type == EventType.MouseUp) { bool ifCursorStayed = Vector2.SqrMagnitude(mousePosStart - Event.current.mousePosition) < SF_Tools.stationaryCursorRadius; if (ifCursorStayed && !SF_GUI.MultiSelectModifierHeld()) { selection.DeselectAll(registerUndo: true); } //editor.Defocus( deselectNodes: ifCursorStayed ); } if (SF_GUI.ReleasedRawLMB()) { SF_NodeConnector.pendingConnectionSource = null; } // If press if (Event.current.type == EventType.MouseDown && MouseInsideNodeView(false)) { //bool ifNotHoldingModifier = !SF_GUI.MultiSelectModifierHeld(); mousePosStart = Event.current.mousePosition; editor.Defocus(); } if (!editor.screenshotInProgress) { Rect logoRect = rect; logoRect.y -= 14; logoRect.x += 1; logoRect.width = SF_GUI.Logo.width; logoRect.height = SF_GUI.Logo.height; GUI.color = new Color(1f, 1f, 1f, 0.5f); GUI.DrawTexture(logoRect, SF_GUI.Logo); logoRect.y += logoRect.height; logoRect.height = 16; GUI.Label(logoRect, "v" + SF_Tools.version, EditorStyles.boldLabel); GUI.color = Color.white; } }
public void Draw(Rect r) { VS_Editor.instance.mousePosition = Event.current.mousePosition; rect = r; Rect localRect = new Rect(r); localRect.x = 0; localRect.y = 0; //View Rect rectInner = new Rect(rect); rectInner.width = float.MaxValue / 2f; rectInner.height = float.MaxValue / 2f; if (Event.current.type == EventType.Repaint) { nodeSpaceMousePos = ScreenSpaceToZoomSpace(Event.current.mousePosition); } bool mouseOverNode = false; //Debug.Log("Zoom Rect (rect) : " + rect); ZoomArea.Begin(zoom, rect, cameraPos); { if (Event.current.type == EventType.Repaint) { viewSpaceMousePos = ZoomSpaceToScreenSpace(Event.current.mousePosition); } if (VS_Editor.instance.nodes != null) { for (int i = VS_Editor.instance.nodes.Count - 1; i >= 0; i--) { if (!VS_Editor.instance.nodes[i].Draw()) { break; } } if (!mouseOverNode) { for (int i = 0; i < VS_Editor.instance.nodes.Count; i++) { if (VS_Editor.instance.nodes[i].MouseOverNode(world: true)) { mouseOverNode = true; } } } if (Event.current.type == EventType.Repaint) { for (int i = 0; i < VS_Editor.instance.nodes.Count; i++) { //Nodes Draw Connectors...... } } } UpdteCutLine(); UpdateCameraPanning(); } ZoomArea.End(zoom); //...... //Check if Editing Any Node Text Field //Check if Node inside the Canvas && if we ScrollWhell if (MouseInsideNodeView(false) && Event.current.type == EventType.ScrollWheel) { zoomTarget = ClampZoom(zoomTarget * (1f - Event.current.delta.y * 0.02f)); Debug.Log(zoomTarget); } //........ SetZoom(Mathf.Lerp(zoom, zoomTarget, 0.2f)); if (Event.current.type == EventType.ContextClick && !VEditorGUI.Utility.HoldingAlt()) { Vector2 mousePos = Event.current.mousePosition; if (rect.Contains(mousePos)) { //GenericMenu menu = new GenericMenu(); VS_Editor.instance.AddNode(); } } //........................ //........................ if (MouseInsideNodeView(false) && Event.current.type == EventType.MouseUp) { bool ifCursorStayed = Vector2.SqrMagnitude(mousePosStart - Event.current.mousePosition) < VS_Tools.stationaryCursorRadius; if (ifCursorStayed && !VEditorGUI.Utility.MultiSelectModifierHeld()) { //Selection Deselect All.... } } //........................ if (Event.current.type == EventType.MouseDown && MouseInsideNodeView(false)) { mousePosStart = Event.current.mousePosition; VS_Editor.instance.Defocus(); } }