string getDirection(ref Vector2 direction) { int directionState = GetComponent<Animator>().GetInteger("DirectionState"); //Quaternion angle = Quaternion.Euler(0, 0, 0); switch (directionState) { case 0: direction.Set(-1, 0); return "Left"; // Left case 1: direction.Set(1, 0); return "Right"; // Right case 2: direction.Set(0, 1); return "Up"; // Up case 3: direction.Set(0, -1); return "Down"; // Down } return ""; }
public static Vector2 ZeroIfCloseToZero(Vector2 input) { Vector2 output = new Vector2(); float x, y; x = Mathf.Abs(input.x) < zeroBuffer ? 0f : input.x; y = Mathf.Abs(input.y) < zeroBuffer ? 0f : input.y; output.Set(x, y); return output; }
public Vector2 LeftCorner() { Vector2 leftCorner = new Vector2(); Vector2 lb = enterTile + ToLeft * leftLength; Vector2 ru = upTile - ToLeft * rightLength; leftCorner.Set(Mathf.Min(lb.x, ru.x), Mathf.Min(lb.y, ru.y)); return leftCorner; }
// Update is called once per frame void Update() { //starfield.transform.position = new Vector3(Camera.main.transform.position.x,Camera.main.transform.position.y, starfield.transform.position.z); //starfield.transform.localScale = new Vector2((1280/(Camera.main.orthographicSize*2)), 1280 / (Camera.main.orthographicSize*2)); if(playerLocations != null) { if(playerLocations.Count > 0) { Vector2 centroid = new Vector2(0,0); foreach(Transform player in playerLocations) { centroid += new Vector2(player.position.x, player.position.y); } centroid.Set((centroid.x+size_offset)/4, (centroid.y+size_offset)/4); float maxDistance = 0; foreach(Transform player in playerLocations) { float tempDistance = getDistance(player.position.x, player.position.y, centroid.x, centroid.y); if(tempDistance > maxDistance) maxDistance = tempDistance; } float distance_percent = (maxDistance / 720.0f) * 1280.0f; distance_percent = (distance_percent / 2.0f) + 50.0f; if(distance_percent < minCameraSize) distance_percent = minCameraSize; if(distance_percent > 800) distance_percent = 800; float current_size = Camera.main.orthographicSize; distance_percent = Mathf.Lerp(current_size, distance_percent, smooth_value); Camera.main.orthographicSize = distance_percent;//Mathf.Clamp(distance_percent, minCameraSize, maxCameraSize); //Debug.Log (distance_percent); float targetX = Mathf.Lerp(transform.position.x, centroid.x, smooth_value * Time.deltaTime); float targetY = Mathf.Lerp(transform.position.y, centroid.y, smooth_value * Time.deltaTime); targetX = Mathf.Clamp(centroid.x, minXAndY.x, maxXAndY.x); targetY = Mathf.Clamp(centroid.y, minXAndY.y, maxXAndY.y); // Set the camera's position to the target position with the same z component. transform.position = new Vector3(targetX, targetY, transform.position.z); //want to be in middle of players and have size be +factor on either side } } }
/// <summary> /// Get perpendicular vectors for giving vector2 /// </summary> /// <param name="v"></param> /// <returns></returns> public static Vector2[] PerpendicularVector2D(Vector2 v) { v = v.normalized; Vector2 pv1 = new Vector2(), pv2 = new Vector2(); float x = v.x, y = v.y, a, b; b = Mathf.Sqrt(1 / (1 + y * y / x * x)); a = -(y / x) * b; pv1.Set(a, b); pv2.Set(-a, -b); return new Vector2[] { pv1, pv2 }; }
// Calculate UVs for our tessellated vertices private Vector2 BezCurveUV(float t, Vector2 p0, Vector2 p1, Vector2 p2) { Vector2 bezPoint = new Vector2(); float a = 1f - t; float tt = t * t; float[] tPoints = new float[2]; for (int i = 0; i < 2; i++) { tPoints [i] = ((a * a) * p0 [i]) + (2 * a) * (t * p1 [i]) + (tt * p2 [i]); } bezPoint.Set(tPoints [0], tPoints [1]); return bezPoint; }
void OnTriggerEnter(Collider col) { //GetComponent<BoxCollider>().enabled = false; // disable the box collider so that we cannot re enter this one // if we have visted the map, then dont post a message to generate a map piece again if (!hasBeenVisited) { NotificationCenter.DefaultCenter().PostNotification(this, "UserGenerateMapPiece", this.gameObject); NotificationCenter.DefaultCenter().PostNotification(this, "OnCarScore"); hasBeenVisited = true; } Vector2 myPosition = new Vector2(); myPosition.Set(this.transform.position.x, this.transform.position.z); // always post that the car has entered though NotificationCenter.DefaultCenter().PostNotification(this, "OnCarEnter", myPosition - previousPosition); }
public void LateUpdate() { ClearMeshData(); if (section == null) { return; } IList <List <Vector3> > segments = cable.sampledCable.Segments; int sectionSegments = section.Segments; int verticesPerSection = sectionSegments + 1; // the last vertex in each section must be duplicated, due to uv wraparound. float vCoord = -uvScale.y * cable.RestLength; // v texture coordinate. int sectionIndex = 0; float strain = cable.sampledCable.Length / cable.RestLength; // we will define and transport a reference frame along the curve using parallel transport method: if (frame == null) { frame = new CurveFrame(); } Vector4 texTangent = Vector4.zero; Vector2 uv = Vector2.zero; Matrix4x4 w2l = transform.worldToLocalMatrix; for (int k = 0; k < segments.Count; ++k) { List <Vector3> samples = segments[k]; // Reinitialize frame for each segment. frame.Reset(); for (int i = 0; i < samples.Count; ++i) { // Calculate previous and next curve indices: int nextIndex = Mathf.Min(i + 1, samples.Count - 1); int prevIndex = Mathf.Max(i - 1, 0); Vector3 point = w2l.MultiplyPoint3x4(samples[i]); Vector3 prevPoint = w2l.MultiplyPoint3x4(samples[prevIndex]); Vector3 nextPoint = w2l.MultiplyPoint3x4(samples[nextIndex]); Vector3 nextV = (nextPoint - point).normalized; Vector3 prevV = (point - prevPoint).normalized; Vector3 tangent = nextV + prevV; // update frame: frame.Transport(point, tangent, 0); // advance v texcoord: vCoord += uvScale.y * (Vector3.Distance(point, prevPoint) / strain); // Loop around each segment: for (int j = 0; j <= sectionSegments; ++j) { vertices.Add(frame.position + (section.vertices[j].x * frame.normal + section.vertices[j].y * frame.binormal) * thickness); normals.Add(vertices[vertices.Count - 1] - frame.position); texTangent = -Vector3.Cross(normals[normals.Count - 1], frame.tangent); texTangent.w = 1; tangents.Add(texTangent); uv.Set((j / (float)sectionSegments) * uvScale.x, vCoord); uvs.Add(uv); if (j < sectionSegments && i < samples.Count - 1) { tris.Add(sectionIndex * verticesPerSection + j); tris.Add(sectionIndex * verticesPerSection + (j + 1)); tris.Add((sectionIndex + 1) * verticesPerSection + j); tris.Add(sectionIndex * verticesPerSection + (j + 1)); tris.Add((sectionIndex + 1) * verticesPerSection + (j + 1)); tris.Add((sectionIndex + 1) * verticesPerSection + j); } } sectionIndex++; } } CommitMeshData(); }
void Update() { // if( Input.GetKeyDown( KeyCode.Escape ) ) // { // Cursor.lockState = CursorLockMode.None; // } // if( Input.GetMouseButtonDown( 0 ) ) // { // Cursor.lockState = CursorLockMode.Locked; // } var aim = new Vector2(Input.GetAxis("Mouse X"), Input.GetAxis("Mouse Y")); if (Cursor.lockState == CursorLockMode.None) { aim.Set(0.0f, 0.0f); } if (aim.y > maxAimMove) { aim.y = maxAimMove; } if (aim.y < -maxAimMove) { aim.y = -maxAimMove; } var tempAng = cam.transform.eulerAngles; tempAng.x = tempAng.x - aim.y * rotationSpeed * Time.deltaTime; if (tempAng.x > 90.0f - verticalCutoff && tempAng.x < 180.0f) { tempAng.x = 90.0f - verticalCutoff; } if (tempAng.x < 270.0f + verticalCutoff && tempAng.x > 180.0f) { tempAng.x = 270.0f + verticalCutoff; } tempAng.y = tempAng.y + aim.x * rotationSpeed * Time.deltaTime; tempAng.z = 0.0f; cam.transform.eulerAngles = tempAng; WeaponStats oldLookItem = lookItem; var ray = new Ray(cam.transform.position, cam.transform.forward); RaycastHit hit; if (Physics.Raycast(ray, out hit, 5.0f, rayMask)) { //for the keg if (Input.GetAxis("Interact") > 0.0f && heldItem != null) { var keg = hit.transform.GetComponentInParent <Keg>(); if (keg != null) { //if the cup type matches the mug type, then give drink if (heldItem.GetComponent <MugData>().DrinkType.Contains(keg.drinkType) && !heldItem.gameObject.name.Contains("Full") && !heldItem.gameObject.name.Contains("Potion")) { Destroy(heldItem.gameObject); var mug = keg.SpawnMug(holdSpot); heldItem = mug.GetComponent <Throwable>().PickUp(holdSpot); GetComponent <SFXPlayer>().PlaySFX("fill cup"); } //else, flash red?(flash doesn't work) else if ((heldItem.GetComponent <MugData>().DrinkType != keg.drinkType)) { keg.GetComponent <Highlightable>().StartFlash(); } } } //if nothing in your hand when picking up if (Input.GetAxis("Interact") > 0.0f && heldItem == null) { //for picking up throwables var throwable = hit.transform.GetComponentInParent <Throwable>(); if (throwable != null) { heldItem = throwable.PickUp(holdSpot); } //for poison var keg = hit.transform.GetComponentInParent <Keg>(); if (keg != null) { if (keg.drinkType == "Poison") { var mug = keg.SpawnMug(holdSpot); heldItem = mug.GetComponent <Throwable>().PickUp(holdSpot); } } //for the cup before the keg var cup = hit.transform.GetComponentInParent <DrinkLocation>(); if (cup != null) { var heldCup = cup.SpawnCup(holdSpot); heldItem = heldCup.GetComponent <Throwable>().PickUp(holdSpot); } //for reference book var refBook = hit.transform.GetComponentInParent <RefBook>(); if (refBook != null) { refBook.Preview(); } } lookItem = hit.transform.GetComponentInParent <WeaponStats>(); hit.transform.GetComponentInParent <Highlightable>()?.Highlight(); } else { lookItem = null; } if (lookItem != oldLookItem && lookItem != null) { UpdateWepInfo(lookItem); } if (lookItem == null) { if (wepInfoClose.Update(Time.deltaTime)) { UpdateWepInfo(null); } } else { wepInfoClose.Reset(); } if (Input.GetAxis("Fire1") > 0.0f && heldItem != null) { heldItem.GetComponent <Throwable>().Throw(cam.transform.forward); heldItem = null; } }
void UpdateMesh() { if (mesh == null) { mesh = GetComponent <MeshFilter>().sharedMesh; if (mesh == null) { mesh = new Mesh(); mesh.hideFlags = HideFlags.DontSave; GetComponent <MeshFilter>().mesh = mesh; } } GetComponent <MeshFilter>().sharedMesh = mesh; mesh.Clear(); portions.Clear(); foreach (GradientColorKey key in gradientColors.colorKeys) { if (!portions.Contains(key.time)) { portions.Add(key.time); } } foreach (GradientAlphaKey key in gradientColors.alphaKeys) { if (!portions.Contains(key.time)) { portions.Add(key.time); } } portions.Sort(); int colorsCount = portions.Count; int parts = colorsCount > 2 ? (colorsCount - 1) : 1; int vertexCount = parts * 2 + 2; Vector3[] meshVertices = new Vector3[vertexCount]; int[] meshTriangles = new int[parts * 2 * 3]; Vector2[] meshUV = new Vector2[vertexCount]; Color[] colors = new Color[vertexCount]; Vector2 halfSize = size * 0.5f; Vector2 firstSize = Vector2.zero; Vector2 secondSize = Vector2.zero; Vector2 anchorOffset = Vector2.zero; switch (anchor) { case AnchorEnum.LowerLeft: case AnchorEnum.LowerCenter: case AnchorEnum.LowerRight: firstSize[(int)gradientDirection] = size[(int)gradientDirection]; secondSize = size; anchorOffset.x = -halfSize.x * (int)anchor; break; case AnchorEnum.MiddleLeft: case AnchorEnum.MiddleCenter: case AnchorEnum.MiddleRight: if (gradientDirection == GradientDirectionEnum.Horizontal) { firstSize.Set(size.x, -halfSize.y); secondSize.Set(size.x, halfSize.y); anchorOffset.x = -halfSize.x * ((int)anchor - 3); } else if (gradientDirection == GradientDirectionEnum.Vertical) { firstSize.y = size.y; secondSize = size; anchorOffset.Set((-halfSize.x * ((int)anchor - 3)), -halfSize.y); } break; case AnchorEnum.UpperLeft: case AnchorEnum.UpperCenter: case AnchorEnum.UpperRight: if (gradientDirection == GradientDirectionEnum.Horizontal) { firstSize.Set(size.x, -size.y); secondSize.x = size.x; anchorOffset.x = -halfSize.x * ((int)anchor - 6); } else if (gradientDirection == GradientDirectionEnum.Vertical) { firstSize.y = size.y; secondSize = size; anchorOffset.Set((-halfSize.x * ((int)anchor - 6)), -size.y); } break; } Vector3 newScale = CachedTransform.localScale; newScale.x = scale.x * sizeMultiplier.x; newScale.y = scale.y * sizeMultiplier.y; CachedTransform.localScale = newScale; for (int i = 0; i < (vertexCount / 2); i++) { if (gradientDirection == GradientDirectionEnum.Horizontal) { meshVertices[2 * i] = new Vector3((anchorOffset.x + firstSize.x * portions[i]), (anchorOffset.y + firstSize.y)); meshVertices[2 * i + 1] = new Vector3((anchorOffset.x + secondSize.x * portions[i]), (anchorOffset.y + secondSize.y)); meshUV[2 * i] = new Vector2(portions[i], 0f); meshUV[2 * i + 1] = new Vector2(portions[i], 1f); } else if (gradientDirection == GradientDirectionEnum.Vertical) { meshVertices[2 * i] = new Vector3((anchorOffset.x + firstSize.x), (anchorOffset.y + firstSize.y * portions[i])); meshVertices[2 * i + 1] = new Vector3((anchorOffset.x + secondSize.x), (anchorOffset.y + secondSize.y * portions[i])); meshUV[2 * i] = new Vector2(0f, portions[i]); meshUV[2 * i + 1] = new Vector2(1f, portions[i]); } meshUV[2 * i].Scale(newScale); meshUV[2 * i + 1].Scale(newScale); colors[2 * i] = colors[2 * i + 1] = gradientColors.Evaluate(portions[i]); } for (int i = 0; i < parts; i++) { meshTriangles[6 * i + 0] = 2 * i; meshTriangles[6 * i + 1] = 2 * i + 1; meshTriangles[6 * i + 2] = 2 * i + 2; meshTriangles[6 * i + 3] = 2 * i + 1; meshTriangles[6 * i + 4] = 2 * i + 3; meshTriangles[6 * i + 5] = 2 * i + 2; } mesh.vertices = meshVertices; mesh.triangles = meshTriangles; mesh.uv = meshUV; mesh.colors = colors; mesh.RecalculateNormals(); mesh.RecalculateBounds(); #if !UNITY_5_5_OR_NEWER mesh.Optimize(); #endif }
// Retourne (angle en degrés, zoom en pixels) public static Vector2 ZoomAndRotatTouch() { Vector2 result = new Vector2(0f, 0f); if(Input.touchCount == 2) { Touch t0 = Input.touches[0]; Touch t1 = Input.touches[1]; if(t0.phase == TouchPhase.Began || t1.phase == TouchPhase.Began) { s_zrtLastT0Pos = t0.position; s_zrtLastT1Pos = t1.position; } else if(t0.phase == TouchPhase.Moved || t1.phase == TouchPhase.Moved) { float curDist = Vector2.Distance(t0.position, t1.position); // float lastDist = Vector2.Distance(s_zrtLastT0Pos, s_zrtLastT1Pos); // -- Rotation -- Vector2 oldDir = s_zrtLastT1Pos - s_zrtLastT0Pos; float angle = Vector2.Angle(oldDir,(t1.position - t0.position)); Vector3 cross = Vector3.Cross(oldDir,(t1.position - t0.position)); if(cross.z < 0) angle = 360 - angle; // -- Zoom -- float startDist = Vector2.Distance(s_zrtLastT0Pos, s_zrtLastT1Pos); result.Set (angle, curDist - startDist); s_zrtLastT0Pos = t0.position; s_zrtLastT1Pos = t1.position; } } // 2 touch return result; }
public static void LookAt2D(this Transform self, Vector2 target, Vector3 axis, float angle) { m_tmpVector2.Set(target.x - self.position.x, target.y - self.position.y); angle = angle + Mathf.Atan2(m_tmpVector2.y, m_tmpVector2.x) * Mathf.Rad2Deg; self.rotation = Quaternion.AngleAxis(angle, axis); }
Vector2 GetScaleForOverride(tk2dCamera settings, tk2dCameraResolutionOverride currentOverride, float width, float height) { Vector2 scale = Vector2.one; float s = 1.0f; if (currentOverride == null) { return(scale); } switch (currentOverride.autoScaleMode) { case tk2dCameraResolutionOverride.AutoScaleMode.PixelPerfect: s = 1; scale.Set(s, s); break; case tk2dCameraResolutionOverride.AutoScaleMode.FitHeight: s = height / settings.nativeResolutionHeight; scale.Set(s, s); break; case tk2dCameraResolutionOverride.AutoScaleMode.FitWidth: s = width / settings.nativeResolutionWidth; scale.Set(s, s); break; case tk2dCameraResolutionOverride.AutoScaleMode.FitVisible: case tk2dCameraResolutionOverride.AutoScaleMode.ClosestMultipleOfTwo: float nativeAspect = (float)settings.nativeResolutionWidth / settings.nativeResolutionHeight; float currentAspect = width / height; if (currentAspect < nativeAspect) { s = width / settings.nativeResolutionWidth; } else { s = height / settings.nativeResolutionHeight; } if (currentOverride.autoScaleMode == tk2dCameraResolutionOverride.AutoScaleMode.ClosestMultipleOfTwo) { if (s > 1.0f) { s = Mathf.Floor(s); // round number } else { s = Mathf.Pow(2, Mathf.Floor(Mathf.Log(s, 2))); // minimise only as power of two } } scale.Set(s, s); break; case tk2dCameraResolutionOverride.AutoScaleMode.StretchToFit: scale.Set(width / settings.nativeResolutionWidth, height / settings.nativeResolutionHeight); break; case tk2dCameraResolutionOverride.AutoScaleMode.Fill: s = Mathf.Max(width / settings.nativeResolutionWidth, height / settings.nativeResolutionHeight); scale.Set(s, s); break; default: case tk2dCameraResolutionOverride.AutoScaleMode.None: s = currentOverride.scale; scale.Set(s, s); break; } return(scale); }
public void ScrollTo(int index, float offset = 0f) { scroll.Set(scroll.x, Styles.HistoryEntryHeight * index + offset); }
Vector2 returnToVerticalPosition() { float upForce=0.4f; float verticalPositionOffset=0.2f; float minimunVerticalPosition=verticalPosition-verticalPositionOffset; Vector2 upVector = new Vector2(); if(transform.position.y<minimunVerticalPosition){ upVector.Set(0, upForce); }else{ upVector.Set(0, 0); } return upVector; }
Vector2 moveLinearMedusa(Vector2 newDirection) { float vectorMagnitud = inverseVectorMagnitude(newDirection.magnitude)*LINEAR_FORCE_MULTIPLIER; Vector2 directionVector = new Vector2(); //print ("Vector Magnitude: " + vectorMagnitud); if (newDirection.x < 0) { directionVector.Set(-1 * vectorMagnitud, 0); } else if (newDirection.x > 0) { directionVector.Set(vectorMagnitud, 0); } else { directionVector.Set(0,0); } return directionVector; }
//protected Cell[] cells; public HallWay(Vector2 start, Vector2 end, Room room0, Room room1) { this.startPos = start; this.endPos = end; this.room0 = room0; this.room1 = room1; cellCount = 0; // vertical if (start.x == end.x) { // force position to decimal so it will be inside of grid if (startPos.x % 1 == 1) { startPos.Set (startPos.x + 0.5f, startPos.y); endPos.Set (endPos.x + 0.5f, endPos.y); } cellCount = (int)(Mathf.Abs (endPos.y - startPos.y)); direction = Direction.Vertical; } // horizontal else { // force position to decimal so it will be inside of grid if (startPos.y % 1 == 1) { startPos.Set (startPos.x, startPos.y + 0.5f); endPos.Set (endPos.x, endPos.y + 0.5f); } cellCount = (int)(Mathf.Abs (endPos.x - startPos.x)); direction = Direction.Horizontal; } //cells = new Cell[size]; }
public Cell[][] ComputeMap(Cell[][] baseMap, Enemy[] enemies, List<List<Vector2>> cellsByEnemy) { Cell[][] im = new Cell[cellsX][]; for (int x = 0; x < cellsX; x++) { im [x] = new Cell[cellsZ]; for (int y = 0; y < cellsZ; y++) { im [x] [y] = baseMap [x] [y].Copy (); } } for (int i = 0; i < enemies.Length; i++) { Enemy enemy = enemies [i]; // For every enemy, get their direction and current world position and scale into IM scale Vector2 dir = new Vector2 (enemy.GetSimulatedForward ().x, enemy.GetSimulatedForward ().z); // Convert enemy position into Grid Coordinates Vector2 pos = new Vector2 ((enemy.GetSimulationPosition ().x - minX) / tileSizeX, (enemy.GetSimulationPosition ().z - minZ) / tileSizeZ); Vector2 p = new Vector2 (); for (int x = -1; x <= 1; x++) for (int y = -1; y <= 1; y++) // Check map boundaries if (Mathf.FloorToInt (pos.x + x) >= 0 && Mathf.FloorToInt (pos.x + x) < cellsX && Mathf.FloorToInt (pos.y + y) >= 0 && Mathf.FloorToInt (pos.y + y) < cellsZ) // (everything here is in world coord, so we must transform back from grid coord to world coord) // If the distance from the position of the guy to the middle of the 4 cells around him is leseer than the radius, we paint those cells if (Vector2.Distance (new Vector2 (enemy.GetSimulationPosition ().x, enemy.GetSimulationPosition ().z), new Vector2 ((Mathf.Floor (pos.x + x) + tileSizeX) * tileSizeX + minX, (Mathf.Floor (pos.y + y) + tileSizeZ) * tileSizeZ + minZ)) < enemy.radius) { im [Mathf.FloorToInt (pos.x + x)] [Mathf.FloorToInt (pos.y + y)].seen = true; cellsByEnemy [i].Add (new Vector2 (pos.x + x, pos.y + y)); } // if tileSizeX != tileSizeZ we can be in big trouble! float dist = enemy.fovDistance / ((tileSizeX + tileSizeZ) / 2); DDA dda = new DDA(tileSizeX, tileSizeZ, cellsX, cellsZ); for (int x = 0; x < cellsX; x++) { for (int y = 0; y < cellsZ; y++) { // Skip cells that are staticly blocked or seen by other enemies // Don't skip cells seen by other enemies or we won't have the correct seenCells computed if (im [x] [y].blocked || im [x] [y].safe) continue; // This enemy haven't seen it yet bool seen = false; for (int px = 0; px <= 1; px++) { for (int py = 0; py <= 1; py++) { // Destination of the ray p.Set (x + px, y + py); // Direction of the ray Vector2 res = (p - pos).normalized; // Is the target within our FoV? if (Vector2.Distance (p, pos) < dist && Vector2.Angle (res, dir) < enemy.fovAngle) { // Check if target is seen by this enemy seen = seen || dda.HasLOS(im, p, pos, res, x, y); } } } // If this enemy has seen it if (seen) cellsByEnemy [i].Add (new Vector2 (x, y)); // Now take into account other enemies before modifying the cells value im [x] [y].seen = im [x] [y].seen || seen; } } } return im; }
void HandleTouchInput() { Touch touch = Input.GetTouch(0); // Handle finger movements based on touch phase. switch (touch.phase) { // Record initial touch position. case TouchPhase.Began: touchInputStartPosition = touch.position; touchDirectionChosen = false; break; // Determine direction by comparing the current touch // position with the initial one. case TouchPhase.Moved: touchDirection = touch.position - touchInputStartPosition; break; // Report that a direction has been chosen when the finger is lifted. case TouchPhase.Ended: touchDirectionChosen = true; break; } if (touchDirectionChosen) { if (touchDirection.y > minSwipe) { this.GetComponent<Rigidbody2D>().AddForce(Vector2.up * jumpForce); } else if (touchDirection.y < -minSwipe){ //playerAnimator.SetTrigger("Slide"); } touchDirection.Set(0f,0f); touchDirectionChosen = false; } }
public virtual void DamageHop(float velocity) { velocityWorkspace.Set(rb.velocity.x, velocity); rb.velocity = velocityWorkspace; }
public static Vector2 Abs(this Vector2 a) { a.Set(Mathf.Abs(a.x), Mathf.Abs(a.y)); return(a); }
private void meleeAttack() { // get position to fire range attack int directionState = anim.GetInteger("DirectionState"); Vector2 direction = new Vector2(0, 0); Quaternion angle = Quaternion.Euler(0, 0, 0); switch (directionState) { case 0: direction.Set(-1, 0); break; // Left case 1: direction.Set(1, 0); break; // Right case 2: direction.Set(0, 1); angle = Quaternion.Euler(0, 0, 90); break; // Up case 3: direction.Set(0, -1); angle = Quaternion.Euler(0, 0, 90); break; // Down } GameObject melee = (GameObject) Instantiate(melee_hitbox, new Vector3(transform.position.x + direction.x * (2f / 3), transform.position.y + direction.y * (2f / 3), 0), angle); melee.transform.parent = gameObject.transform; // preform animation anim.SetTrigger("Melee"); // add attack to stats PlayerStats.getStats(PID).attacksDone++; }
private void AddVert(VertexHelper vertexHelper, float posX, float posY, float uvX, float uvY) { cachedPosition.Set(posX, posY, 0); cachedUv.Set(uvX, uvY); vertexHelper.AddVert(cachedPosition, color, cachedUv, kVec2Zero, kVec2Zero, kVec2Zero, kVec3Zero, kVec4Zero); }
public void generate() { Vector2 position = new Vector2(); Quaternion rotation = new Quaternion(); for (int i = 0; i < map1.GetLength(0); i++) { for (int j = 0; j < map1.GetLength(1); j++) { position.Set(0.5f + j, 0.5f - i); switch (map1[i, j]) { case 0: mapComponentsList.Add(Network.Instantiate(wall, position, rotation, 1)); break; case 1: { GameObject g = Network.Instantiate(tile, position, rotation, 1) as GameObject; mapComponentsList.Add(g); //tileList.Add(g); float x=Random.Range(1,100); if (x/5 == 1) { //monsterList.Add(Network.Instantiate(monster, position, rotation, 0)); } if(x==6){ //add chest; } } break; case 2: if (map1[i - 1, j] == 0 && map1[i + 1, j] == 0) mapComponentsList.Add(Network.Instantiate(door2, position, rotation, 1)); if (map1[i, j - 1] == 0 && map1[i, j + 1] == 0) mapComponentsList.Add(Network.Instantiate(door1, position, rotation, 1)); break; case 3: mapComponentsList.Add(Network.Instantiate(water, position, rotation, 1)); break; case 4: mapComponentsList.Add(Network.Instantiate(crossroads, position, rotation, 1)); break; case 5: mapComponentsList.Add(Network.Instantiate(lava, position, rotation, 1)); break; case 6: mapComponentsList.Add(Network.Instantiate(hole, position, rotation, 1)); break; case 7: mapComponentsList.Add(Network.Instantiate(fog, position, rotation, 1)); break; case 8: mapComponentsList.Add(Network.Instantiate(safe, position, rotation, 1)); break; case 9: mapComponentsList.Add(Network.Instantiate(teleport, position, rotation, 1)); break; case 12: if (map1[i - 1, j] == 0 || map1[i + 1, j] == 0) { astro = Network.Instantiate(stairv, position, rotation, 1) as GameObject; mapComponentsList.Add(astro); } else if (map1[i, j - 1] == 0 || map1[i, j + 1] == 0) { astro = Network.Instantiate(stairh, position, rotation, 1) as GameObject; mapComponentsList.Add(astro); } if(lastMap<whichMap){ if(map1[i-1,j]==0) position.Set(position.x-1,position.y); else if(map1[i+1,j]==0) position.Set(position.x+1,position.y); else if(map1[i,j-1]==0) position.Set(position.x,position.y-1); else position.Set(position.x,position.y+1); spawnPosition.position.Set(position.x,position.y,0); } astro.gameObject.tag = "Down"; break; case 21: //player.transform.position.Set(position[0], position[1], 1); if (map1[i - 1, j] == 0 || map1[i + 1, j] == 0){ astro = Network.Instantiate(stairv, position, rotation, 1) as GameObject; mapComponentsList.Add(astro); } else if (map1[i, j - 1] == 0 || map1[i, j + 1] == 0){ astro = Network.Instantiate(stairh, position, rotation, 1) as GameObject; mapComponentsList.Add(astro); } if(lastMap>whichMap){ if(map1[i-1,j]==0) position.Set(position.x-1,position.y); else if(map1[i+1,j]==0) position.Set(position.x+1,position.y); else if(map1[i,j-1]==0) position.Set(position.x,position.y-1); else position.Set(position.x,position.y+1); spawnPosition.position.Set(position.x,position.y,0); } astro.gameObject.tag = "Up"; break; } } } }
// Called automatically by Unity once every Physics step. void FixedUpdate() { if (IsMine) { m_attacking = m_myController.IsAttacking; m_moving = m_myController.IsMoving || (m_lastPosition - transform.position).sqrMagnitude < 0.1; m_jumping = m_myController.IsJumping; m_movement.Set(m_myController.MoveInput.x, m_myController.MoveInput.y); UpdateInputBlocking(); float player_speed = FrontEnd.World.Instance.fPlayer.speed; maxForwardSpeed = 4.0f + 8.0f * (player_speed / (player_speed + 1000f)); } CacheAnimatorState(); EquipMeleeWeapon(IsWeaponEquiped()); m_Animator.SetFloat(m_HashStateTime, Mathf.Repeat(m_Animator.GetCurrentAnimatorStateInfo(0).normalizedTime, 1f)); m_Animator.ResetTrigger(m_HashMeleeAttack); if (m_attacking && canAttack) { m_Animator.SetTrigger(m_HashMeleeAttack); if (IsMine) { m_myController.SendAttackingAction(); } } CalculateForwardMovement(); CalculateVerticalMovement(); SetTargetRotation(); if (IsOrientationUpdated() && m_moving) { UpdateOrientation(); } if (!IsMine) { /* * m_CharCtrl.Move(newPosition - transform.position); * m_CharCtrl.transform.rotation.Set(newRotation.x, newRotation.y, newRotation.z, newRotation.w); * m_IsGrounded = m_CharCtrl.isGrounded; * * // If Ellen is not on the ground then send the vertical speed to the animator. * // This is so the vertical speed is kept when landing so the correct landing animation is played. * if (!m_IsGrounded) * m_Animator.SetFloat(m_HashAirborneVerticalSpeed, m_VerticalSpeed); * * // Send whether or not Ellen is on the ground to the animator. * m_Animator.SetBool(m_HashGrounded, m_IsGrounded); */ //m_moving = false; m_jumping = false; m_attacking = false; } PlayAudio(); TimeoutToIdle(); m_PreviouslyGrounded = m_IsGrounded; // detect attack target UpdateAttackTarget(); }
private void meleeAttack() { // get position to fire range attack int directionState = anim.GetInteger("DirectionState"); Vector2 direction = new Vector2(0, 0); Quaternion angle = Quaternion.Euler(0, 0, 0); switch (directionState) { case 0: direction.Set(-1, 0); break; // Left case 1: direction.Set(1, 0); break; // Right case 2: direction.Set(0, 1); angle = Quaternion.Euler(0, 0, 90); break; // Up case 3: direction.Set(0, -1); angle = Quaternion.Euler(0, 0, 90); break; // Down } // preforms melee attack network wide Cmd_MeleeAttack(direction,angle); // preform animation anim.SetTrigger("Melee"); }
// Charge l'objectif id du fichier XML au chemin path dans l'objectif courant void load(string path, int id) { // Variables servant à récupérer l'information int tag = 0; Vector2 coords = new Vector2 (); Regex coordRegexX = new Regex (@"[0-9]+,[0-9]+;$"); Match coordMatchX; Regex coordRegexY = new Regex (@";[0-9]+,[0-9]+$"); Match coordMatchY; //Variable de test Boolean aTrouve = false; XmlTextReader myXmlTextReader = new XmlTextReader (path); while(myXmlTextReader.Read()){ if(myXmlTextReader.IsStartElement() && myXmlTextReader.Name == "objectifs") { Debug.Log(nbObjectifs); nbObjectifs = int.Parse(myXmlTextReader.GetAttribute("number")); Debug.Log(nbObjectifs); } if(myXmlTextReader.IsStartElement() && myXmlTextReader.Name == "objectif"){ if (int.Parse(myXmlTextReader.GetAttribute("id")) == id){ aTrouve = true; ObjectifId = id; initialObjective.description = myXmlTextReader.GetAttribute("description"); currentObjective.description = myXmlTextReader.GetAttribute("description"); tag = int.Parse(myXmlTextReader.GetAttribute("tag")); //Si le tag est 10, il s'agit d'un blend de caméra if(tag == 14) { StartCoroutine(waitObjectif(float.Parse(myXmlTextReader.GetAttribute("time")))); currentObjective.tableDesObjectifs.Add(tag, -1); return; } else if(tag == 10) { Debug.Log("Blend"); currentObjective.tableDesObjectifs.Add(tag, -1); float x = float.Parse(myXmlTextReader.GetAttribute("x")); float y = float.Parse(myXmlTextReader.GetAttribute("y")); float z = float.Parse(myXmlTextReader.GetAttribute("z")); float duration = float.Parse(myXmlTextReader.GetAttribute("duration")); float size = float.Parse(myXmlTextReader.GetAttribute("size")); bool enableControlAfter = bool.Parse(myXmlTextReader.GetAttribute("enableControlAfter")); StartCoroutine(CameraControl.BlendCameraTo(new Vector3(x,y,z),size,duration,enableControlAfter)); } else if(tag == 11) // Si c'est 11, il s'agit d'un affichage de panneau { currentObjective.tableDesObjectifs.Add(tag, -1); string learning = myXmlTextReader.GetAttribute("learning"); GameObject panelLearning = GameObject.Find(learning); if (panelLearning != null) { if(panelLearning.GetComponent<PanelController>()!= null) panelLearning.GetComponent<PanelController> ().isPanelActive = true; } else { Debug.Log("Panneau Learning " + learning +" non trouvé, penser à activer l'objet !"); loadNextObjectif(); return; } } else if(tag == 8) { initialObjective.tableDesObjectifs.Add(tag, (int)int.Parse(myXmlTextReader.GetAttribute("value"))); currentObjective.tableDesObjectifs.Add(tag, 0); string cutsceneName = myXmlTextReader.GetAttribute("cutsceneName"); GameObject cutscene = GameObject.Find(cutsceneName); if(cutscene != null) { Cutscene scriptCutscene = cutscene.GetComponent<Cutscene>(); if(scriptCutscene != null) cutscene.GetComponent<Cutscene>().enabled = true; else { Debug.Log("Aucun script cutscene n'est attaché à l'objet"); loadNextObjectif(); return; } } else { Debug.Log("Cutscene " + cutsceneName +" non trouvé, penser à activer l'objet !"); loadNextObjectif(); return; } } else if(tag == 0 || tag == 1 || tag == 3 || tag == 4 || tag == 6 || tag == 7 || tag == 9 || tag == 12 || tag == 13) { // Si on a ces tags, on a forcément un int dans value initialObjective.tableDesObjectifs.Add(tag, (int)int.Parse(myXmlTextReader.GetAttribute("value"))); currentObjective.tableDesObjectifs.Add(tag, 0); break; } else if(tag == 2) { // Pour le tag 2, on récupère un vector2 dans value sous forme "float;float" coordMatchX = coordRegexX.Match(myXmlTextReader.GetAttribute("value")); coordMatchY = coordRegexY.Match(myXmlTextReader.GetAttribute("value")); coords.Set(float.Parse(coordMatchX.Value), float.Parse(coordMatchY.Value)); initialObjective.tableDesObjectifs.Add(tag, (Vector2)coords); currentObjective.tableDesObjectifs.Add(tag, (Vector2)coords); break; } else if(tag == 5) { // Pour le tag 5 on a un float dans value initialObjective.tableDesObjectifs.Add(tag, (float)float.Parse(myXmlTextReader.GetAttribute("value"))); currentObjective.tableDesObjectifs.Add(tag, (float)float.Parse(myXmlTextReader.GetAttribute("value"))); StartCoroutine(TimeObjectif()); break; } } } } if (aTrouve) { //StartCoroutine(GameManager.gameManager.GetComponent<LevelBacteriaManager>().makeTransition (1, 1)); } else { Debug.Log ("N'a pas trouvé.\n"); } }
private void rangeAttack() { // get position to fire range attack int directionState = anim.GetInteger("DirectionState"); Vector2 direction = new Vector2(0,0); Quaternion angle = Quaternion.Euler(0,0,0); switch (directionState) { case 0: direction.Set(-1, 0); angle = Quaternion.Euler(0, 0, 90); break; // Left case 1: direction.Set(1, 0); angle = Quaternion.Euler(0, 0, -90); break; // Right case 2: direction.Set(0, 1); angle = Quaternion.Euler(0, 0, 0); break; // Up case 3: direction.Set(0, -1); angle = Quaternion.Euler(0, 0, 180); break; // Down } GameObject projectile = (GameObject)Instantiate(ranged_hitbox, new Vector3(transform.position.x + direction.x * (2f / 3), transform.position.y + direction.y * (2f / 3), 0), angle); projectile.GetComponent<Rigidbody2D>().velocity = direction * PROJECTILE_SPEED; projectile.GetComponent<CauseKnockback>().my_parent_name = name; //tell it who made it // preform animation anim.SetTrigger("Range"); }
// Update is called once per frame, i.e. every time the game computes a new image (an uncertain rate) // It could be 20 images per second on a slow computer, or 3000 on a very fast one // To give the impression of movement, a game (just like a movie) is still images that are shown at high speed. Typically in games, 30 or 60 images show in one second. Each of those images is called a frame. // In this Update function, you will write anything you want to happen continuously in the game (for example, reading input from the player, moving GameObjects, or counting time passing). void Update() { // make the Ruby GameObject move horizontal = Input.GetAxis("Horizontal"); // be ready to tie the character's movement to keyboard input // keyboard input through axes // It stores the result that Input.GetAxis ("Horizontal") provides // using the Unity Input System, which is composed of Input Settings and input code // which Unity gives you to query the value of an axis for that frame vertical = Input.GetAxis("Vertical"); // The default axis corresponding to the key up and down is called Vertical /*Debug.Log(horizontal);*/ // Debug contains all functions that help debug your game Vector2 move = new Vector2(horizontal, vertical); // Instead of doing x and y independently for the movement, you store the input amount in a Vector2 called move if (!Mathf.Approximately(move.x, 0.0f) || !Mathf.Approximately(move.y, 0.0f)) // Check to see whether move.x or move.y isn’t equal to 0 // Use Mathf.Approximately instead of == because the way computers store float numbers means there is a tiny loss in precision // you should never test for perfect equality // because an operation that should end up giving 0.0f could instead give something like 0.0000000001f instead { lookDirection.Set(move.x, move.y); // If either x or y isn’t equal to 0, then Ruby is moving, set your look direction to your Move Vector and Ruby should look in the direction that she is moving. // If she stops moving (Move x and y are 0) then that won’t happen and look will remain as the value it was just before she stopped moving. // equal to lookDirection = move lookDirection.Normalize(); // In general, you will normalize vectors that store direction because length is not important, only the direction is } animator.SetFloat("Look X", lookDirection.x); // send the direction you look in and the speed (the length of the move vector) to the Animator // If Ruby doesn’t move, it will be 0, but if she does then it will be a positive number. animator.SetFloat("Look Y", lookDirection.y); animator.SetFloat("Speed", move.magnitude); if (isInvincible) { invincibleTimer -= Time.deltaTime; // if Ruby is invincible, you remove deltaTime from your timer if (invincibleTimer < 0) // When that time is less than or equal to zero, the timer reaches its end and Ruby’s invincibility is finished, { isInvincible = false; // so you remove her invincibility by resetting the bool to false } } if (Input.GetKeyDown(KeyCode.C)) // when the player presses a key, and call Launch when they do { Launch(); // launch a Cog } if (Input.GetKeyDown(KeyCode.X)) // if the “talk” button is pressed, enter the if block and start your Raycast { // RaycastHit2D is a variable stores the result of a Raycast, which is given to us by Physics2D.Raycast RaycastHit2D hit = Physics2D.Raycast(rigidbody2D.position + Vector2.up * 0.2f, lookDirection, 1.5f, LayerMask.GetMask("NPC")); // The starting point is an upward offset from Ruby’s position because you want to test from the centre of Ruby’s Sprite, not from her feet. // The direction, which is the direction that Ruby is looking // A layer mask which allows us to test only certain layers. Any layers that are not part of the mask will be ignored during the intersection test. if (hit.collider != null) // If the Raycast didn’t intersect anything, this will be null so do nothing // Otherwise, RaycastHit2D will contain the Collider the Raycast intersected { /*Debug.Log("Raycast has hit the object " + hit.collider.gameObject);*/ // log the object you have just found with the Raycast NonPlayerCharacter character = hit.collider.GetComponent <NonPlayerCharacter>(); // trying to find a NonPlayerCharacter script on the object the Raycast hit if (character != null) // if that script exists on that object, you will display the dialog { character.DisplayDialog(); } } } }
// ------------------------------------------- // Recursive Calculs // ------------------------------------------- /// <summary> /// Calculates complex collisions recursively. /// </summary> private void RecursiveComplexCollisions(Vector2 _velocity, Vector2 _normal, int _recursiveCount = 0) { int _amount = CastCollider(_velocity, extraCastBuffer, out float _distance); // No movement mean object is stuck into something, so return. if (_distance == 0) { return; } if (_amount == 0) { rigidbody.position += _velocity; GroundSnap(_velocity, _normal); //semiSolidCollider = null; return; } // Move rigidbody and get extra cast velocity. if ((_distance -= Physics2D.defaultContactOffset) > 0) { Vector2 _normalizedVelocity = _velocity.normalized; rigidbody.position += _normalizedVelocity * _distance; _velocity = _normalizedVelocity * (_velocity.magnitude - _distance); } // If reached recursion limit, stop. if (_recursiveCount > collisionSystemRecursionCeil) { InsertCastInfos(extraCastBuffer, _amount); GroundSnap(_velocity, _normal); return; } // Get velocity outside normal surface, as pure value. float _angle = Vector2.SignedAngle(_normal, _velocity); _normal.Set(0, 1); _velocity = RotateVector(_normal, _angle) * _velocity.magnitude; Vector2 _hitNormal = extraCastBuffer[0].normal; _velocity = ClimbStep(_velocity, extraCastBuffer[0]); if ((Mathf.Abs(extraCastBuffer[0].normal.x) == 1) && (_velocity.x != 0)) { for (int _i = 1; _i < _amount; _i++) { InsertCastInfo(extraCastBuffer[_i]); } } else { InsertCastInfos(extraCastBuffer, _amount); } if (_velocity != null) { // Reduce extra movement according to main impact normals. _velocity -= _hitNormal * Vector2.Dot(_velocity, _hitNormal); if (_velocity != null) { RecursiveComplexCollisions(_velocity, _normal, _recursiveCount + 1); } } }
// Update is called once per frame void Update() { if (!gameOverState) { horizontal = Input.GetAxis("Horizontal"); vertical = Input.GetAxis("Vertical"); Vector2 position = rigidbody2d.position; position.x = position.x + speed * horizontal * Time.deltaTime; position.y = position.y + speed * vertical * Time.deltaTime; Vector2 move = new Vector2(horizontal, vertical); if (!Mathf.Approximately(move.x, 0.0f) || !Mathf.Approximately(move.y, 0.0f)) { lookDirection.Set(move.x, move.y); lookDirection.Normalize(); startedRunning = true; } else if (Mathf.Approximately(move.x, 0.0f) || Mathf.Approximately(move.y, 0.0f)) { isRunning = false; startedRunning = false; runningAudio.Stop(); } if (startedRunning && !isRunning) { isRunning = true; runningAudio.Play(); } animator.SetFloat("Look X", lookDirection.x); animator.SetFloat("Look Y", lookDirection.y); animator.SetFloat("Speed", move.magnitude); position = position + move * speed * Time.deltaTime; rigidbody2d.MovePosition(position); if (isInvincible) { invincibleTimer -= Time.deltaTime; if (invincibleTimer < 0) { isInvincible = false; } } if (Input.GetKeyDown(KeyCode.C)) { Launch(); characterOneShot(cogThrowClip); } if (Input.GetKeyDown(KeyCode.X)) { RaycastHit2D hit = Physics2D.Raycast(rigidbody2d.position + Vector2.up * 0.2f, lookDirection, 1.5f, LayerMask.GetMask("NPC")); if (hit.collider != null) { NonPlayerCharacter character = hit.collider.GetComponent <NonPlayerCharacter>(); if (character != null) { character.DisplayDialog(); } } } DamagaeFlash(false); HealFlash(false); } }
/* // Create a new bitmap. Bitmap bmp = new Bitmap("c:\\fakePhoto.jpg"); // Lock the bitmap's bits. Rectangle rect = new Rectangle(0, 0, bmp.Width, bmp.Height); System.Drawing.Imaging.BitmapData bmpData = bmp.LockBits(rect, System.Drawing.Imaging.ImageLockMode.ReadWrite, bmp.PixelFormat); // Get the address of the first line. IntPtr ptr = bmpData.Scan0; // Declare an array to hold the bytes of the bitmap. int bytes = Math.Abs(bmpData.Stride) * bmp.Height; ��� byte[] rgbValues = new byte[bytes]; // Copy the RGB values into the array. System.Runtime.InteropServices.Marshal.Copy(ptr, rgbValues, 0, bytes); // Set every third value to 255. A 24bpp bitmap will look red. for (int counter = 2; counter < rgbValues.Length; counter += 3) rgbValues[counter] = 255; // Copy the RGB values back to the bitmap System.Runtime.InteropServices.Marshal.Copy(rgbValues, 0, ptr, bytes); // Unlock the bits. bmp.UnlockBits(bmpData); // Draw the modified image. e.Graphics.DrawImage(bmp, 0, 150); */ /*private void FromBitmap(Bitmap b,Int32[,] pole){ for(int i = 0;i<b.Width;i++) for(int j = 0;j<b.Height;j++){ pole[i,j] = b.GetPixel(i,j).ToArgb(); } } private unsafe Bitmap ToBitmap(Int32[,] pole){ Bitmap b; fixed(int* pp = &pole[0,0]) b= new Bitmap(pole.GetLength(1), pole.GetLength(0),pole.GetLength(1)*4, System.Drawing.Imaging.PixelFormat.Format32bppArgb,(IntPtr)pp); return b; }*/ void OnPaint(object sender, PaintEventArgs e) { //= new Bitmap(e.ClipRectangle.Width, e.ClipRectangle.Height, e.Graphics); //MyUnion union; if((e.ClipRectangle.Height != oldy) || (e.ClipRectangle.Width != oldx)) { pole = new Int32[e.ClipRectangle.Height,e.ClipRectangle.Width]; oldx = e.ClipRectangle.Width; oldy = e.ClipRectangle.Height; }else{Array.Clear(pole, 0, pole.Length);} //byte[] bytes = new byte[b.Width*b.Height*4]; //Int32[,] pole = new Int32[b.Width,b.Height]; Soft3DScreen s = new Soft3DScreen(pole); Triangle3D t3; Triangle2D t2; s.ViewMatrix.Translate(0,0,-5); s.ViewMatrix.RotateX(rx); s.ViewMatrix.RotateY(ry); Vector2 texcoord1 = new Vector2(-1,-1); Vector2 texcoord2 = new Vector2(-1,1); Vector2 texcoord3 = new Vector2(1,-1); Vector3 v1 = new Vector3(-1,-1,-1); Vector3 v2 = new Vector3(-1,1,-1); Vector3 v3 = new Vector3(1,-1,-1); t3 = new Triangle3D(v1,v2,v3); t2 = new Triangle2D(texcoord1,texcoord2,texcoord3); TexturedTriangle ttriangle = new TexturedTriangle(t3,t2,texture); s.DrawTexturedTriangle3d(ttriangle); texcoord1.Set(-1,1); texcoord2.Set(1,1); texcoord3.Set(1,-1); v1.Set(-1,1,-1); v2.Set(1,1,-1); v3.Set(1,-1,-1); t3 = new Triangle3D(v1,v2,v3); t2 = new Triangle2D(texcoord1,texcoord2,texcoord3); ttriangle = new TexturedTriangle(t3,t2,texture); s.DrawTexturedTriangle3d(ttriangle); /* s.ActualColor = Color.White.ToArgb(); v1.Set(-1,1,1); v2.Set(1,1,1); v3.Set(1,-1,1); //t3 = new Triangle3D(v1,v2,v3); s.DrawFilledTriangle3d(v1,v2,v3); v1.Set(-1,1,1); v2.Set(-1,-1,1); v3.Set(1,-1,1); //t3 = new Triangle3D(v1,v2,v3); s.DrawFilledTriangle3d(v1,v2,v3); s.ActualColor = Color.Green.ToArgb(); v1.Set(1,1,1); v2.Set(1,1,-1); v3.Set(1,-1,1); //t3 = new Triangle3D(v1,v2,v3); s.DrawFilledTriangle3d(v1,v2,v3); v1.Set(1,-1,-1); v2.Set(1,1,-1); v3.Set(1,-1,1); //t3 = new Triangle3D(v1,v2,v3); s.DrawFilledTriangle3d(v1,v2,v3); s.ActualColor = Color.Blue.ToArgb(); v1.Set(-1,1,1); v2.Set(-1,1,-1); v3.Set(-1,-1,1); //t3 = new Triangle3D(v1,v2,v3); s.DrawFilledTriangle3d(v1,v2,v3);; v1.Set(-1,-1,-1); v2.Set(-1,1,-1); v3.Set(-1,-1,1); //t3 = new Triangle3D(v1,v2,v3); s.DrawFilledTriangle3d(v1,v2,v3); s.ActualColor = Color.Cyan.ToArgb(); v1.Set(1,1,1); v2.Set(1,1,-1); v3.Set(-1,1,1); //t3 = new Triangle3D(v1,v2,v3); s.DrawFilledTriangle3d(v1,v2,v3); v1.Set(-1,1,-1); v2.Set(-1,1,1); v3.Set(1,1,-1); //t3 = new Triangle3D(v1,v2,v3); s.DrawFilledTriangle3d(v1,v2,v3); s.ActualColor = Color.Orange.ToArgb(); v1.Set(1,-1,1); v2.Set(1,-1,-1); v3.Set(-1,-1,1); //t3 = new Triangle3D(v1,v2,v3); s.DrawFilledTriangle3d(v1,v2,v3); v1.Set(-1,-1,-1); v2.Set(1,-1,-1); v3.Set(-1,-1,1); //t3 = new Triangle3D(v1,v2,v3); s.DrawFilledTriangle3d(v1,v2,v3);*/ Bitmap b = Soft3DBitmap.ToBitmap(pole); e.Graphics.DrawImageUnscaled(b, 0, 0); //e.Graphics.DrawImageUnscaled(texture, 0, 0); }
private void Hit_Hitscan(Vector2 end, int bullets) { objects.Clear(); startPos.Set(transform.position.x, transform.position.y); RaycastHit2D[] hits = Physics2D.LinecastAll(startPos, end); int penetrationCount = 0; trailEnd.Set(end.x, end.y); foreach (RaycastHit2D hit in hits) { if (penetrationCount >= Damage.Penetration) { break; } // A hit to a collider... Health h = hit.collider.gameObject.GetComponentInParent <Health>(); if (h == null) { //Debug.Log("Object hit has no health, cannot be destroyed!"); // DEBATE - Do we allow to shoot through non destructible objects, that may have multiple colliders? // Hell no! // UNLESS - the collider is a trigger! if (hit.collider.isTrigger) { //Debug.Log("Collider we hit is a trigger, continue..."); continue; } trailEnd.Set(hit.point.x, hit.point.y); float angle = Mathf.Atan2(hit.normal.y, hit.normal.x) * Mathf.Rad2Deg + 180; HitEffect.Spawn(hit.point, angle, hit.collider, true); break; } // Do not allow to hit local player : Maybe some sort of team system??? EDIT - Done. Player p = h.GetComponent <Player>(); if (p != null) { if (p == Player.Local._Player) { continue; } if (Teams.I.PlayersInSameTeam(Player.Local.Name, p.Name)) { continue; // Do not allow team damage from guns. TODO IMPLEMENT GAMES RULES. } } if (!h.CanHit) { continue; } if (h.CannotHit.Contains(hit.collider)) { continue; } if (hit.collider.gameObject.GetComponent <NeverHitMe>() != null) { continue; } if (objects.Contains(h)) // Do not allow multiple hits to one object. { continue; } if (hit.collider.gameObject.GetComponentInParent <Item>() != null) { // Is item, may be held in hands. Ignore. continue; } objects.Add(h); float damage = GetDamage(startPos, hit.point, penetrationCount, bullets); if (damage != 0) { CmdHitObject(h.gameObject, Player.Local.Name + ":" + gun.Item.Prefab, damage); float angle = Mathf.Atan2(hit.normal.y, hit.normal.x) * Mathf.Rad2Deg + 180; HitEffect.Spawn(hit.point, angle, hit.collider, true); } penetrationCount++; if (penetrationCount >= Damage.Penetration) { trailEnd.Set(hit.point.x, hit.point.y); } //Debug.Log("Hit object, can penetrate :" + h.CanPenetrate); if (!h.CanPenetrate) { trailEnd.Set(hit.point.x, hit.point.y); break; } } // Spawn visual line... GameObject GO = ObjectPool.Instantiate(GunEffects.Instance.BulletTrail.gameObject, PoolType.BULLET_PATH); GO.GetComponent <BulletPath>().Setup(GetBulletSpawn().position, trailEnd); CmdSpawnBulletTrail(GetBulletSpawn().position, trailEnd); objects.Clear(); }
// void OnDrawGizmos () { // Debug.Log ("_________________________"); // Debug.Log (counter); // Debug.Log ("_________________________"); // if (vertices == null || counter == 5) // return; // Gizmos.color = Color.black; // for (int i = 0; i <vertices.Length; i++) { // //Debug.Log (i); // if (vertices [i] != null) { // Gizmos.DrawSphere (vertices [i], .05f); // Debug.Log (vertices[i]); // Debug.Log("Point: "+vertices[i/2]); // } else { // Debug.Log ("NULL"); // } // } // } // Use this for initialization void Start() { lastRightFence = new Vector3 (); lastLeftFence = new Vector3 (); lastLeftDxDy = new Vector3 (); lastRightDxDy = new Vector3 (); Mesh mesh = new Mesh (); MeshFilter m = GetComponent<MeshFilter>(); m.mesh.Clear (); // string text = System.IO.File.ReadAllText(Application.dataPath + "/Scripts/WriteToFile.txt"); string[] lines = text.Split ('\n'); string sep = "\t"; Vector3 oldV = new Vector3(); List<Vector3> array = new List<Vector3> (); for (int i=0; i<lines.Length-1; i++) { string s = lines [i]; string[] split = s.Split (sep.ToCharArray()); float x = float.Parse (split [0]); float y = float.Parse (split [1]); float z = float.Parse (split [2]); Vector3 tempp = new Vector3 (x, y, z); if (Vector3.Magnitude (tempp - oldV) < MIN_DISTANCE) continue; array.Add(tempp); oldV = tempp; } Vector3[] sampleinput = array.ToArray (); vertices = new Vector3[sampleinput.Length * 2]; float dz = sampleinput[1].z - sampleinput[0].z; float dx = sampleinput[1].x - sampleinput[0].x; temp.Set (-1 * dz, dx); temp.Normalize(); temp *= width; float moveZ = temp.y; float moveX = temp.x; vertices [0] = new Vector3 (sampleinput [0].x + moveX, 0, sampleinput [0].z + moveZ); vertices [1] = new Vector3 (sampleinput [0].x - moveX, 0, sampleinput [0].z - moveZ); //------------------------------------------------------- Transform fence = GameObject.FindGameObjectWithTag("FenceHolder").transform; ArrayList fences = new ArrayList (); for (int i = 1; i < sampleinput.Length-1; i++) { // if (i % 10 == 0) { // GameObject o = Instantiate (Resources.Load ("BetterFence"), sampleinput [i], Quaternion.identity) as GameObject; // o.transform.SetParent (fence); // fences.Add (o); // } dz = sampleinput[i+1].z - sampleinput[i-1].z; dx = sampleinput[i+1].x - sampleinput[i-1].x; temp.Set (-1 * dz, dx); temp.Normalize(); temp *= width; moveZ = temp.y; moveX = temp.x; vertices [i*2] = new Vector3 (sampleinput [i].x + moveX, 0, sampleinput [i].z + moveZ); vertices [i*2 + 1] = new Vector3 (sampleinput [i].x - moveX, 0, sampleinput [i].z - moveZ); if (lastLeftFence == null || Vector3.Distance(lastLeftFence,vertices[i*2]) > FENCE_LENGTH) { Vector3 tempp; if (lastLeftDxDy == null) { tempp = vertices [i * 2]; lastLeftDxDy.Set (moveX, 0, moveZ); lastLeftDxDy.Normalize (); } else { tempp = lastLeftFence + (lastLeftDxDy * FENCE_LENGTH / 2); lastLeftDxDy.Set (moveX, 0, moveZ); lastLeftDxDy.Normalize (); tempp += (lastLeftDxDy * FENCE_LENGTH / 2); } lastLeftFence = vertices [i * 2]; float angle = Mathf.Atan (lastLeftDxDy.x / lastLeftDxDy.z); Quaternion q = new Quaternion (); q.SetEulerRotation (0, angle, 0); GameObject o1 = Instantiate (Resources.Load ("BetterFence"), tempp,q) as GameObject; //GameObject o2 = Instantiate (Resources.Load ("BetterFence"), vertices[i*2+1],q) as GameObject; o1.transform.SetParent (fence); //o2.transform.SetParent (fence); fences.Add (o1); //fences.Add (o2); //lastLeftDxDy.Set(moveX,0,moveZ); } if (lastRightFence == null || Vector3.Distance(lastRightFence,vertices[i*2+1]) > FENCE_LENGTH) { Vector3 tempp; if (lastRightDxDy == null) { tempp = vertices [i * 2+1]; lastRightDxDy.Set (moveX, 0, moveZ); lastRightDxDy.Normalize (); } else { tempp = lastRightFence + (lastRightDxDy * FENCE_LENGTH / 2); lastRightDxDy.Set (moveX, 0, moveZ); lastRightDxDy.Normalize (); tempp += (lastRightDxDy * FENCE_LENGTH / 2); } lastRightFence = vertices [i * 2+1]; float angle = Mathf.Atan (temp.x / temp.y); Quaternion q = new Quaternion (); q.SetEulerRotation (0, angle, 0); //GameObject o1 = Instantiate (Resources.Load ("BetterFence"), vertices[i*2],q) as GameObject; GameObject o2 = Instantiate (Resources.Load ("BetterFence"), vertices[i*2+1],q) as GameObject; //o1.transform.SetParent (fence); o2.transform.SetParent (fence); //fences.Add (o1); fences.Add (o2); } } //setup last one dz = sampleinput[sampleinput.Length-1].z - sampleinput[sampleinput.Length-2].z; dx = sampleinput[sampleinput.Length-1].x - sampleinput[sampleinput.Length-2].x; temp.Set (-1 * dz, dx); temp.Normalize(); temp *= width; moveZ = temp.y; moveX = temp.x; vertices [2*(sampleinput.Length-1)] = new Vector3 (sampleinput [sampleinput.Length-1].x + moveX, 0, sampleinput [sampleinput.Length-1].z + moveZ); vertices [2*(sampleinput.Length-1)+1] = new Vector3 (sampleinput [sampleinput.Length-1].x - moveX, 0, sampleinput [sampleinput.Length-1].z - moveZ); mesh.vertices = vertices; //num triangles Vector2[] uvs = new Vector2[vertices.Length]; for (int i = 0; i < uvs.Length - 3; i += 4) { uvs [i] = new Vector2 (1, 1); uvs [i+1] = new Vector2 (0, 1); uvs [i+2] = new Vector2 (1, 0); uvs [i+3] = new Vector2 (0, 0); } int[] indices = new int[(sampleinput.Length * 2-2)*3]; for (int i = 0; i < sampleinput.Length * 2 - 2; i++) { if (i % 2 == 0 && i!= sampleinput.Length-1) { indices [i * 3] = i; indices [i * 3 + 1] = i + 3; indices [i * 3 + 2] = i + 1; } else { indices [i * 3] = i - 1; indices [i * 3 + 1] = i + 1; indices [i * 3 + 2] = i + 2; } } mesh.triangles = indices; mesh.uv = uvs; UnityEditor.AssetDatabase.CreateAsset (mesh, "Assets/createdmesh/trackmesh.asset"); //UnityEditor.AssetDatabase.CreateAsset (GameObject.FindGameObjectWithTag ("FenceHolder"), "Assets/createdmesh/fences.asset"); //Object prefab = EditorUtility.CreateEmptyPrefab("Assets/Temporary/"+t.gameObject.name+".prefab"); //Object prefab = UnityEditor.PrefabUtility.FindPrefabRoot(GameObject.FindGameObjectWithTag("AllFences")); //Prefab prefab = Resources.Load("AllFences"); //UnityEditor.PrefabUtility.ReplacePrefab(GameObject.FindGameObjectWithTag("FenceHolder"),prefab,UnityEditor.ReplacePrefabOptions.ConnectToPrefab); UnityEditor.AssetDatabase.SaveAssets (); GetComponent<MeshCollider> ().sharedMesh = mesh; print ("Here"); this.enabled = false; }
void Move() { vec.Set(GameManager.instance.pi.xMove * speed, GameManager.instance.pi.yMove * speed); rigid.velocity = vec; }
void UpdateAcceleration() { // Newton Second Law acceleration = massInv * force; force.Set(0.0f, 0.0f); }
/// <summary> /// Shifts the original target position in accordance with target leading, range estimation and weather/lighting effects /// </summary> public virtual void ShiftTarget(ShiftVecReport report, bool calculateMechanicalOnly = false, bool isInstant = false) { if (!calculateMechanicalOnly) { Vector3 u = caster.TrueCenter(); sourceLoc.Set(u.x, u.z); if (numShotsFired == 0) { // On first shot of burst do a range estimate estimatedTargDist = report.GetRandDist(); } Vector3 v = report.target.Thing?.TrueCenter() ?? report.target.Cell.ToVector3Shifted(); //report.targetPawn != null ? report.targetPawn.DrawPos + report.targetPawn.Drawer.leaner.LeanOffset * 0.5f : report.target.Cell.ToVector3Shifted(); if (report.targetPawn != null) { v += report.targetPawn.Drawer.leaner.LeanOffset * 0.5f; } newTargetLoc.Set(v.x, v.z); // ----------------------------------- STEP 1: Actual location + Shift for visibility //FIXME : GetRandCircularVec may be causing recoil to be unnoticeable - each next shot in the burst has a new random circular vector around the target. newTargetLoc += report.GetRandCircularVec(); // ----------------------------------- STEP 2: Estimated shot to hit location newTargetLoc = sourceLoc + (newTargetLoc - sourceLoc).normalized * estimatedTargDist; // Lead a moving target if (!isInstant) { newTargetLoc += report.GetRandLeadVec(); } // ----------------------------------- STEP 3: Recoil, Skewing, Skill checks, Cover calculations rotationDegrees = 0f; angleRadians = 0f; GetSwayVec(ref rotationDegrees, ref angleRadians); GetRecoilVec(ref rotationDegrees, ref angleRadians); // Height difference calculations for ShotAngle float targetHeight = 0f; var coverRange = new CollisionVertical(report.cover).HeightRange; //Get " " cover, assume it is the edifice // Projectiles with flyOverhead target the surface in front of the target if (Projectile.projectile.flyOverhead) { targetHeight = coverRange.max; } else { var victimVert = new CollisionVertical(currentTarget.Thing); var targetRange = victimVert.HeightRange; //Get lower and upper heights of the target if (targetRange.min < coverRange.max) //Some part of the target is hidden behind some cover { // - It is possible for targetRange.max < coverRange.max, technically, in which case the shooter will never hit until the cover is gone. // - This should be checked for in LoS -NIA targetRange.min = coverRange.max; // Target fully hidden, shift aim upwards if we're doing suppressive fire if (targetRange.max <= coverRange.max && CompFireModes?.CurrentAimMode == AimMode.SuppressFire) { targetRange.max = coverRange.max * 2; } } else if (currentTarget.Thing is Pawn) { // Aim for center of mass on an exposed target targetRange.min = victimVert.BottomHeight; targetRange.max = victimVert.MiddleHeight; } targetHeight = VerbPropsCE.ignorePartialLoSBlocker ? 0 : targetRange.Average; } if (projectilePropsCE.isInstant) { angleRadians += Mathf.Atan2(targetHeight - ShotHeight, (newTargetLoc - sourceLoc).magnitude); } else { angleRadians += ProjectileCE.GetShotAngle(ShotSpeed, (newTargetLoc - sourceLoc).magnitude, targetHeight - ShotHeight, Projectile.projectile.flyOverhead, projectilePropsCE.Gravity); } } // ----------------------------------- STEP 4: Mechanical variation // Get shotvariation, in angle Vector2 RADIANS. Vector2 spreadVec = (projectilePropsCE.isInstant && projectilePropsCE.damageFalloff) ? new Vector2(0, 0) : report.GetRandSpreadVec(); // ----------------------------------- STEP 5: Finalization var w = (newTargetLoc - sourceLoc); shotRotation = (-90 + Mathf.Rad2Deg * Mathf.Atan2(w.y, w.x) + rotationDegrees + spreadVec.x) % 360; shotAngle = angleRadians + spreadVec.y * Mathf.Deg2Rad; }
private void frameReset() { parentController.impactStrengthPercent = 0f; inputVelocity.Set(0f, 0f); displacement.Set(0f, 0f); }
// Update is called once per frame void Update() { Offset = thismaterial.mainTextureOffset; Offset.Set(0, Offset.y + (ScrollSpeed * Time.deltaTime)); thismaterial.mainTextureOffset = Offset; }
IEnumerator Create() { #region Create Random Size & Pos Rooms int counter = 0; int roomAmount = 25; int widthSum = 0; int heightSum = 0; while (counter < roomAmount) { Room room = CreateRandRoom(); room.name = counter.ToString(); rooms.Add(room); counter++; // sum width/height widthSum += room.Width; heightSum += room.Height; yield return(new WaitForSeconds(0.05f)); } #endregion #region Remove Small Rooms float widthMean = widthSum / roomAmount; float heightMean = heightSum / roomAmount; yield return(new WaitForSeconds(4)); for (int i = 0; i < rooms.Count; i++) { //rooms[i].RemovePhysics(); rooms [i].ResetRect(); if (rooms [i].Width < widthMean || rooms [i].Height < heightMean) { Destroy(rooms [i].gameObject); rooms.Remove(rooms [i]); i--; } } yield return(new WaitForSeconds(0.5f)); #endregion #region Create room connection using DelaunayTriangles _points = new List <Vector2> (); for (int i = 0; i < rooms.Count; i++) { _points.Add(rooms [i].Position); } Rect rect = GetMinRect(rooms); Voronoi v = new Voronoi(_points, null, rect); _edges = v.VoronoiDiagram(); _spanningTree = v.SpanningTree(KruskalType.MINIMUM); _delaunayTriangulation = v.DelaunayTriangulation(); #endregion #region Extra Loop Connection int maxExtraPathAmt = (int)(_delaunayTriangulation.Count * 0.1f); int rand = Random.Range(1, maxExtraPathAmt); Debug.Log(rand); while (rand > 0) { int randIndex = Random.Range(0, _delaunayTriangulation.Count); if (_spanningTree.Contains(_delaunayTriangulation [randIndex])) { continue; } else { _spanningTree.Add(_delaunayTriangulation [randIndex]); rand--; } } yield return(new WaitForSeconds(0.5f)); #endregion #region Create HallWays for (int i = 0; i < _spanningTree.Count; i++) { yield return(new WaitForSeconds(0.2f)); Room room0 = GetRoomFromPos(_spanningTree [i].p0); Room room1 = GetRoomFromPos(_spanningTree [i].p1); Debug.Log("Creating Hallway Between " + room0.name + " " + room1.name); float xDistance = Mathf.Abs(room0.Position.x - room1.Position.x); float yDistance = Mathf.Abs(room0.Position.y - room1.Position.y); float xMidPointDistance = xDistance / 2; float yMidPointDistance = yDistance / 2; #region Close in X-Axis // mid x point is inside of both rects if (room0.Position.x + xMidPointDistance < room0.rectMaxX && // removed equal sign ==> 避免房间刚好快要重叠,防止做路径时麻烦,因为路径瓦片可能会刚好在网格线上 room1.Position.x + xMidPointDistance < room1.rectMaxX) { Vector2 startPoint = Vector2.zero; Vector2 endPoint = Vector2.zero; // room0 above room1 if (room0.Position.y >= room1.Position.y) { // room0 left to room1 if (room0.Position.x <= room1.Position.x) { startPoint.Set(room0.Position.x + xMidPointDistance, room0.rectMinY); endPoint.Set(room1.Position.x - xMidPointDistance, room1.rectMaxY); } // room1 left to room0 else if (room0.Position.x > room1.Position.x) { startPoint.Set(room0.Position.x - xMidPointDistance, room0.rectMinY); endPoint.Set(room1.Position.x + xMidPointDistance, room1.rectMaxY); } } // room1 above room0 else if (room0.Position.y < room1.Position.y) { // room0 left to room1 if (room0.Position.x <= room1.Position.x) { startPoint.Set(room0.Position.x + xMidPointDistance, room0.rectMaxY); endPoint.Set(room1.Position.x - xMidPointDistance, room1.rectMinY); } // room1 left to room0 else if (room0.Position.x > room1.Position.x) { startPoint.Set(room0.Position.x - xMidPointDistance, room0.rectMaxY); endPoint.Set(room1.Position.x + xMidPointDistance, room1.rectMinY); } } #endregion // create vertical line HallWay hallway = new HallWay(startPoint, endPoint, room0, room1); _hallways.Add(hallway); room0.AddHallWay(hallway); Debug.Log("##CloseXAxis created hallway from " + startPoint + " to " + endPoint + " between " + room0.name + " " + room1.name); } #region Close In Y-Axis // mid y point is inside of both rects else if (room0.Position.y + yMidPointDistance < room0.rectMaxY && room1.Position.y + yMidPointDistance < room1.rectMaxY) { Vector2 startPoint = Vector2.zero; Vector2 endPoint = Vector2.zero; // room0 above room1 if (room0.Position.y >= room1.Position.y) { // room0 left to room1 if (room0.Position.x <= room1.Position.x) { startPoint.Set(room0.rectMaxX, room0.Position.y - yMidPointDistance); endPoint.Set(room1.rectMinX, room1.Position.y + yMidPointDistance); } // room1 left to room0 else if (room0.Position.x > room1.Position.x) { startPoint.Set(room0.rectMinX, room0.Position.y - yMidPointDistance); endPoint.Set(room1.rectMaxX, room1.Position.y + yMidPointDistance); } } // room1 above room0 else if (room0.Position.y < room1.Position.y) { // room0 left to room1 if (room0.Position.x <= room1.Position.x) { startPoint.Set(room0.rectMaxX, room0.Position.y + yMidPointDistance); endPoint.Set(room1.rectMinX, room1.Position.y - yMidPointDistance); } // room1 left to room0 else if (room0.Position.x > room1.Position.x) { startPoint.Set(room0.rectMinX, room0.Position.y + yMidPointDistance); endPoint.Set(room1.rectMaxX, room1.Position.y - yMidPointDistance); } } // create vertical line HallWay hallway = new HallWay(startPoint, endPoint, room0, room1); _hallways.Add(hallway); room0.AddHallWay(hallway); Debug.Log("##CloseYAxis created hallway from " + startPoint + " to " + endPoint + " between " + room0.name + " " + room1.name); } #endregion #region Far In Both Axis // create L shape hall way else { Vector2 startPoint = Vector2.zero; Vector2 turnPoint = Vector2.zero; Vector2 endPoint = Vector2.zero; // room0 above room1 if (room0.Position.y >= room1.Position.y) { // room0 left to room1 if (room0.Position.x <= room1.Position.x) { startPoint.Set(room0.rectMaxX, room0.Position.y); turnPoint.Set(room0.Position.x + xDistance, room0.Position.y); endPoint.Set(room1.Position.x, room1.rectMaxY); #region Check If Line Collider With Other Room if (LineHasCollision(startPoint, turnPoint, room0.Collider) || LineHasCollision(turnPoint, endPoint, room1.Collider)) { // go other way startPoint.Set(room0.Position.x, room0.rectMinY); turnPoint.Set(room0.Position.x, room0.Position.y - yDistance); endPoint.Set(room1.rectMinX, room1.Position.y); Debug.Log("go other way"); } // still has collision, delete this segment from spanning tree if (LineHasCollision(startPoint, turnPoint, room0.Collider) || LineHasCollision(turnPoint, endPoint, room1.Collider)) { Debug.Log("still collision, remove path"); _spanningTree.RemoveAt(i); i--; continue; } #endregion } // room1 left to room0 else if (room0.Position.x > room1.Position.x) { startPoint.Set(room0.rectMinX, room0.Position.y); turnPoint.Set(room0.Position.x - xDistance, room0.Position.y); endPoint.Set(room1.Position.x, room1.rectMaxY); #region Check If Line Collider With Other Room if (LineHasCollision(startPoint, turnPoint, room0.Collider) || LineHasCollision(turnPoint, endPoint, room1.Collider)) { // go other way startPoint.Set(room0.Position.x, room0.rectMinY); turnPoint.Set(room0.Position.x, room0.Position.y - yDistance); endPoint.Set(room1.rectMaxX, room1.Position.y); Debug.Log("go other way"); } // still has collision, delete this segment from spanning tree if (LineHasCollision(startPoint, turnPoint, room0.Collider) || LineHasCollision(turnPoint, endPoint, room1.Collider)) { Debug.Log("still collison, delete path"); _spanningTree.RemoveAt(i); i--; continue; } #endregion } } // room1 above room0 else if (room0.Position.y < room1.Position.y) { // room0 left to room1 if (room0.Position.x <= room1.Position.x) { startPoint.Set(room0.Position.x, room0.rectMaxY); turnPoint.Set(room0.Position.x, room0.Position.y + yDistance); endPoint.Set(room1.rectMinX, room1.Position.y); #region Check If Line Collider With Other Room if (LineHasCollision(startPoint, turnPoint, room0.Collider) || LineHasCollision(turnPoint, endPoint, room1.Collider)) { // go other way startPoint.Set(room0.rectMaxX, room0.Position.y); turnPoint.Set(room0.Position.x + xDistance, room0.Position.y); endPoint.Set(room1.Position.x, room1.rectMinY); Debug.Log("go other way"); } // still has collision, delete this segment from spanning tree if (LineHasCollision(startPoint, turnPoint, room0.Collider) || LineHasCollision(turnPoint, endPoint, room1.Collider)) { Debug.Log("still collision, delete path"); _spanningTree.RemoveAt(i); i--; continue; } #endregion } // room1 left to room0 else if (room0.Position.x > room1.Position.x) { startPoint.Set(room1.rectMaxX, room1.Position.y); turnPoint.Set(room1.Position.x + xDistance, room1.Position.y); endPoint.Set(room0.Position.x, room0.rectMaxY); #region Check If Line Collider With Other Room if (LineHasCollision(startPoint, turnPoint, room1.Collider) || LineHasCollision(turnPoint, endPoint, room0.Collider)) { // go other way startPoint.Set(room1.Position.x, room1.rectMinY); turnPoint.Set(room1.Position.x, room1.Position.y - yDistance); endPoint.Set(room0.rectMinX, room0.Position.y); Debug.Log("go other way"); } // still has collision, delete this segment from spanning tree if (LineHasCollision(startPoint, turnPoint, room1.Collider) || LineHasCollision(turnPoint, endPoint, room0.Collider)) { Debug.Log("still collision, delete path"); _spanningTree.RemoveAt(i); i--; continue; } #endregion } } // create vertical line LHallWay hallway = new LHallWay(startPoint, turnPoint, endPoint, room0, room1); _hallways.Add(hallway); room0.AddHallWay(hallway); Debug.Log("##Lshape created hallway from " + startPoint + " to " + turnPoint + " to " + endPoint + " between " + room0.name + " " + room1.name); } #endregion } #endregion #region Remove Physics for (int i = 0; i < rooms.Count; i++) { rooms [i].RemovePhysics(); } #endregion #region Create Tiles for (int i = 0; i < rooms.Count; i++) { rooms [i].Fill(); yield return(new WaitForSeconds(0.2f)); } //for (int i = 0; i < _hallways.Count; i++) { // _hallways [i].Fill (); // yield return new WaitForSeconds (0.2f); //} #endregion }
public virtual void SetVelocity(float velocity) { velocityWorkspace.Set(facingDirection * velocity, rb.velocity.y); rb.velocity = velocityWorkspace; }
void Update() { isPressed = false; bool storedState = isTouching; // mouse //#if UNITY_STANDALONE || UNITY_EDITOR || UNITY_WEBPLAYER if (!isTouching && Input.GetMouseButtonDown(0)) { isPressed = true; isTouching = true; touchPoint = usedCamera.ScreenToWorldPoint(Input.mousePosition); screenTouchPoint = Input.mousePosition; } else if (Input.GetMouseButtonUp(0)) { isTouching = false; } else if (isTouching) { touchPoint = usedCamera.ScreenToWorldPoint(Input.mousePosition); screenTouchPoint = Input.mousePosition; } //#else // fingers if (Input.touchCount > 0) { touches = Input.touches; isTouching = true; Touch t = Input.GetTouch(0); if (t.phase == TouchPhase.Began) { isPressed = true; touchPoint = usedCamera.ScreenToWorldPoint(touches[0].position); screenTouchPoint = touches[0].position; } else if (t.phase == TouchPhase.Moved) { touchPoint = usedCamera.ScreenToWorldPoint(touches[0].position); screenTouchPoint = touches[0].position; } else if (t.phase == TouchPhase.Ended) { isTouching = false; } } //#endif // if (isTouching != storedState) { touchPointStored.Set(touchPoint.x, touchPoint.y); if (isTouching) { touchPointPressed.Set(touchPoint.x, touchPoint.y); } else { touchPointUpped.Set(touchPoint.x, touchPoint.y); } isUpped = !isTouching; } if (isTouching) { touchCounter = (++touchCounter) % 5; if (touchCounter == 0) { touchDelta = touchPoint - touchPointStored; touchPointStored.Set(touchPoint.x, touchPoint.y); } } }
/// <summary> /// Handle movement,IFrames, user input /// </summary> void Update() { float horizontal = Input.GetAxis("Horizontal"); float vertical = Input.GetAxis("Vertical"); Vector2 move = new Vector2(horizontal, vertical); if (!Mathf.Approximately(move.x, 0.0f) || !Mathf.Approximately(move.y, 0.0f)) { lookDirection.Set(move.x, move.y); lookDirection.Normalize(); GetComponent <AudioSource>().UnPause(); } else { GetComponent <AudioSource>().Pause(); } animator.SetFloat("Look X", lookDirection.x); animator.SetFloat("Look Y", lookDirection.y); animator.SetFloat("Speed", move.magnitude); Vector2 position = rigidbody2d.position; moveSpeed = (Input.GetKey(KeyCode.LeftShift)) ? (speed * sprintSpeedMultiplier) : speed; position = position + move * moveSpeed * Time.deltaTime; rigidbody2d.MovePosition(position); if (isInvincible) { invincibleTimer -= Time.deltaTime; if (invincibleTimer < 0) { isInvincible = false; } } if (Input.GetKeyDown(KeyCode.C)) { Launch(); PlaySound(thrownClip); } if (Input.GetKeyDown(KeyCode.X)) { RaycastHit2D hit = Physics2D.Raycast(rigidbody2d.position + Vector2.up * 0.2f, lookDirection, 1.5f, LayerMask.GetMask("NPC")); if (hit.collider != null) { NonPlayerCharacter character = hit.collider.GetComponent <NonPlayerCharacter>(); if (character != null) { if (oppController.opponentsLeft != 0) { //begin text character.DisplayDialog(false); } else { //complete text character.DisplayDialog(true); PlaySound(questComplete); } } } } if (Input.GetKeyDown(KeyCode.P)) { Debug.Log(oppController.opponentsLeft); } }
public static void Update() { // standalone #if UNITY_EDITOR Vector3 p = Input.mousePosition; if (s_touching) { s_deltaPos.Set(p.x - s_pos.x, p.y - s_pos.y); if (Input.GetMouseButtonUp(0)) { s_touching = false; s_pos.Set(p.x, p.y); DispatchLuaEvent(TOUCH_END); } else if (s_deltaPos.x != 0 || s_deltaPos.y != 0) { s_pos.Set(p.x, p.y); DispatchLuaEvent(TOUCH_MOVE); } } else { if (Input.GetMouseButtonDown(0)) { s_touching = true; s_pos.Set(p.x, p.y); s_deltaPos.Set(0, 0); DispatchLuaEvent(TOUCH_BEGIN); } } // mobile #else int touchCount = Input.touchCount; if (touchCount == 0) { // 容错 if (s_touching) { s_touching = false; s_deltaPos.Set(0, 0); DispatchLuaEvent(TOUCH_END); } return; } Touch touch; Vector2 p; int i; if (s_touching) { for (i = 0; i < touchCount; i++) { touch = Input.GetTouch(i); if (touch.fingerId == s_id) { p = touch.position; s_deltaPos.Set(p.x - s_pos.x, p.y - s_pos.y); if (touch.phase == TouchPhase.Ended || touch.phase == TouchPhase.Canceled) { s_touching = false; s_pos.Set(p.x, p.y); DispatchLuaEvent(TOUCH_END); } else if (s_deltaPos.x != 0 || s_deltaPos.y != 0) { s_pos.Set(p.x, p.y); DispatchLuaEvent(TOUCH_MOVE); } break; } } } else { for (i = 0; i < touchCount; i++) { touch = Input.GetTouch(i); if (touch.phase == TouchPhase.Began) { s_touching = true; s_id = touch.fingerId; p = touch.position; s_pos.Set(p.x, p.y); s_deltaPos.Set(0, 0); DispatchLuaEvent(TOUCH_BEGIN); break; } } } #endif }
Matrix4x4 GetProjectionMatrixForOverride(tk2dCamera settings, tk2dCameraResolutionOverride currentOverride, float pixelWidth, float pixelHeight, bool halfTexelOffset, out Rect screenExtents, out Rect unscaledScreenExtents) { Vector2 scale = GetScaleForOverride(settings, currentOverride, pixelWidth, pixelHeight); Vector2 offset = GetOffsetForOverride(settings, currentOverride, scale, pixelWidth, pixelHeight); float left = offset.x, bottom = offset.y; float right = pixelWidth + offset.x, top = pixelHeight + offset.y; Vector2 nativeResolutionOffset = Vector2.zero; bool usingLegacyViewportClipping = false; // Correct for viewport clipping rendering // Coordinates in subrect are "native" pixels, but origin is from the extrema of screen if (this.viewportClippingEnabled && this.InheritConfig != null) { float vw = (right - left) / scale.x; float vh = (top - bottom) / scale.y; Vector4 sr = new Vector4((int)this.viewportRegion.x, (int)this.viewportRegion.y, (int)this.viewportRegion.z, (int)this.viewportRegion.w); usingLegacyViewportClipping = true; float viewportLeft = -offset.x / pixelWidth + sr.x / vw; float viewportBottom = -offset.y / pixelHeight + sr.y / vh; float viewportWidth = sr.z / vw; float viewportHeight = sr.w / vh; if (settings.cameraSettings.orthographicOrigin == tk2dCameraSettings.OrthographicOrigin.Center) { viewportLeft += (pixelWidth - settings.nativeResolutionWidth * scale.x) / pixelWidth / 2.0f; viewportBottom += (pixelHeight - settings.nativeResolutionHeight * scale.y) / pixelHeight / 2.0f; } Rect r = new Rect(viewportLeft, viewportBottom, viewportWidth, viewportHeight); if (UnityCamera.rect.x != viewportLeft || UnityCamera.rect.y != viewportBottom || UnityCamera.rect.width != viewportWidth || UnityCamera.rect.height != viewportHeight) { UnityCamera.rect = r; } float maxWidth = Mathf.Min(1.0f - r.x, r.width); float maxHeight = Mathf.Min(1.0f - r.y, r.height); float rectOffsetX = sr.x * scale.x - offset.x; float rectOffsetY = sr.y * scale.y - offset.y; if (settings.cameraSettings.orthographicOrigin == tk2dCameraSettings.OrthographicOrigin.Center) { rectOffsetX -= settings.nativeResolutionWidth * 0.5f * scale.x; rectOffsetY -= settings.nativeResolutionHeight * 0.5f * scale.y; } if (r.x < 0.0f) { rectOffsetX += -r.x * pixelWidth; maxWidth = (r.x + r.width); } if (r.y < 0.0f) { rectOffsetY += -r.y * pixelHeight; maxHeight = (r.y + r.height); } left += rectOffsetX; bottom += rectOffsetY; right = pixelWidth * maxWidth + offset.x + rectOffsetX; top = pixelHeight * maxHeight + offset.y + rectOffsetY; } else { if (UnityCamera.rect != CameraSettings.rect) { UnityCamera.rect = CameraSettings.rect; } // By default the camera is orthographic, bottom left, 1 pixel per meter if (settings.cameraSettings.orthographicOrigin == tk2dCameraSettings.OrthographicOrigin.Center) { float w = (right - left) * 0.5f; left -= w; right -= w; float h = (top - bottom) * 0.5f; top -= h; bottom -= h; nativeResolutionOffset.Set(-nativeResolutionWidth / 2.0f, -nativeResolutionHeight / 2.0f); } } float zoomScale = 1.0f / ZoomFactor; // Only need the half texel offset on PC/D3D, when not running in d3d11 mode bool isWebPlayer = false; #if !UNITY_5_4_OR_NEWER isWebPlayer = Application.platform == RuntimePlatform.WindowsWebPlayer; #endif bool needHalfTexelOffset = (Application.platform == RuntimePlatform.WindowsPlayer || isWebPlayer || Application.platform == RuntimePlatform.WindowsEditor); float halfTexel = (halfTexelOffset && needHalfTexelOffset && SystemInfo.graphicsShaderLevel < 40) ? 0.5f : 0.0f; float orthoSize = settings.cameraSettings.orthographicSize; switch (settings.cameraSettings.orthographicType) { case tk2dCameraSettings.OrthographicType.OrthographicSize: orthoSize = 2.0f * settings.cameraSettings.orthographicSize / settings.nativeResolutionHeight; break; case tk2dCameraSettings.OrthographicType.PixelsPerMeter: orthoSize = 1.0f / settings.cameraSettings.orthographicPixelsPerMeter; break; } // Fixup for clipping if (!usingLegacyViewportClipping) { float clipWidth = Mathf.Min(UnityCamera.rect.width, 1.0f - UnityCamera.rect.x); float clipHeight = Mathf.Min(UnityCamera.rect.height, 1.0f - UnityCamera.rect.y); if (clipWidth > 0 && clipHeight > 0) { scale.x /= clipWidth; scale.y /= clipHeight; } } float s = orthoSize * zoomScale; screenExtents = new Rect(left * s / scale.x, bottom * s / scale.y, (right - left) * s / scale.x, (top - bottom) * s / scale.y); unscaledScreenExtents = new Rect(nativeResolutionOffset.x * s, nativeResolutionOffset.y * s, nativeResolutionWidth * s, nativeResolutionHeight * s); // Near and far clip planes are tweakable per camera, so we pull from current camera instance regardless of inherited values return(OrthoOffCenter(scale, orthoSize * (left + halfTexel) * zoomScale, orthoSize * (right + halfTexel) * zoomScale, orthoSize * (bottom - halfTexel) * zoomScale, orthoSize * (top - halfTexel) * zoomScale, UnityCamera.nearClipPlane, UnityCamera.farClipPlane)); }
// Update is called once per frame void Update() { horizontal = Input.GetAxis("Horizontal"); vertical = Input.GetAxis("Vertical"); Vector2 move = new Vector2(horizontal, vertical); if (!Mathf.Approximately(move.x, 0.0f) || !Mathf.Approximately(move.y, 0.0f)) { lookDirection.Set(move.x, move.y); lookDirection.Normalize(); } animator.SetFloat("Look X", lookDirection.x); animator.SetFloat("Look Y", lookDirection.y); animator.SetFloat("Speed", move.magnitude); if (isInvincible) { invincibleTimer -= Time.deltaTime; if (invincibleTimer < 0) { isInvincible = false; } } if (canShoot == 1) { if (Input.GetKeyDown(KeyCode.C)) { Launch(); } } if (Input.GetKeyDown(KeyCode.X)) { RaycastHit2D hit = Physics2D.Raycast(rigidbody2d.position + Vector2.up * 0.2f, lookDirection, 1.5f, LayerMask.GetMask("Door")); if (hit.collider != null) { scr_door door = hit.collider.GetComponent <scr_door>(); if (door != null) { if (key >= 1) { door.OpenDoor(); key--; } } } } if (currentHealth <= 0) { if (lives == 0) { SceneManager.LoadScene(sceneName: "Lose"); } currentHealth = maxHealth; SceneReload(); } if (canShoot >= 1) { canShoot = 1; } }
private void ScrollTo(int index, float offset = 0f) { scroll.Set(scroll.x, EntryHeight * index + offset); }
/// <summary> /// Updates the camera matrix to ensure 1:1 pixel mapping /// </summary> public void UpdateCameraMatrix() { if (!this.viewportClippingEnabled) inst = this; if (!mainCamera.orthographic) { // Must be orthographic Debug.LogError("tk2dCamera must be orthographic"); mainCamera.orthographic = true; } tk2dCamera settings = inheritSettings != null ? inheritSettings : this; bool viewportClippingEnabled = this.viewportClippingEnabled && this.screenCamera != null && this.screenCamera.rect == unitRect; Camera screenCamera = viewportClippingEnabled ? this.screenCamera : mainCamera; float pixelWidth = screenCamera.pixelWidth; float pixelHeight = screenCamera.pixelHeight; #if UNITY_EDITOR if (settings.forceResolutionInEditor) { pixelWidth = settings.forceResolution.x; pixelHeight = settings.forceResolution.y; } #endif _targetResolution = new Vector2(pixelWidth, pixelHeight); // Find an override if necessary if (!settings.enableResolutionOverrides) currentResolutionOverride = null; if (settings.enableResolutionOverrides && (currentResolutionOverride == null || (currentResolutionOverride != null && (currentResolutionOverride.width != pixelWidth || currentResolutionOverride.height != pixelHeight)) )) { currentResolutionOverride = null; // find one if it matches the current resolution if (settings.resolutionOverride != null) { foreach (var ovr in settings.resolutionOverride) { if (ovr.Match((int)pixelWidth, (int)pixelHeight)) { currentResolutionOverride = ovr; break; } } } } Vector2 scale = new Vector2(1, 1); Vector2 offset = new Vector2(0, 0); float s = 0.0f; if (currentResolutionOverride != null) { switch (currentResolutionOverride.autoScaleMode) { case tk2dCameraResolutionOverride.AutoScaleMode.FitHeight: s = pixelHeight / nativeResolutionHeight; scale.Set(s, s); break; case tk2dCameraResolutionOverride.AutoScaleMode.FitWidth: s = pixelWidth / nativeResolutionWidth; scale.Set(s, s); break; case tk2dCameraResolutionOverride.AutoScaleMode.FitVisible: case tk2dCameraResolutionOverride.AutoScaleMode.PixelPerfectFit: float nativeAspect = (float)nativeResolutionWidth / nativeResolutionHeight; float currentAspect = pixelWidth / pixelHeight; if (currentAspect < nativeAspect) s = pixelWidth / nativeResolutionWidth; else s = pixelHeight / nativeResolutionHeight; if (currentResolutionOverride.autoScaleMode == tk2dCameraResolutionOverride.AutoScaleMode.PixelPerfectFit) { if (s > 1.0f) s = Mathf.Floor(s); // round number else s = Mathf.Pow(2, Mathf.Floor(Mathf.Log(s, 2))); // minimise only as power of two } scale.Set(s, s); break; case tk2dCameraResolutionOverride.AutoScaleMode.StretchToFit: scale.Set(pixelWidth / nativeResolutionWidth, pixelHeight / nativeResolutionHeight); break; default: case tk2dCameraResolutionOverride.AutoScaleMode.None: s = currentResolutionOverride.scale; scale.Set(s, s); break; } scale *= zoomScale; // no offset when ScaleToFit if (currentResolutionOverride.autoScaleMode != tk2dCameraResolutionOverride.AutoScaleMode.StretchToFit) { switch (currentResolutionOverride.fitMode) { case tk2dCameraResolutionOverride.FitMode.Center: offset = new Vector2(Mathf.Round((nativeResolutionWidth * scale.x - pixelWidth ) / 2.0f), Mathf.Round((nativeResolutionHeight * scale.y - pixelHeight) / 2.0f)); break; default: case tk2dCameraResolutionOverride.FitMode.Constant: offset = -currentResolutionOverride.offsetPixels; break; } } } float left = offset.x, bottom = offset.y; float right = pixelWidth + offset.x, top = pixelHeight + offset.y; // Correct for viewport clipping rendering // Coordinates in subrect are "native" pixels, but origin is from the extrema of screen if (viewportClippingEnabled) { float vw = (right - left) / scale.x; float vh = (top - bottom) / scale.y; Vector4 sr = new Vector4((int)viewportRegion.x, (int)viewportRegion.y, (int)viewportRegion.z, (int)viewportRegion.w); float viewportLeft = sr.x / vw; float viewportBottom = sr.y / vh; float viewportWidth = sr.z / vw; float viewportHeight = sr.w / vh; Rect r = new Rect( viewportLeft, viewportBottom, viewportWidth, viewportHeight ); if (mainCamera.rect.x != viewportLeft || mainCamera.rect.y != viewportBottom || mainCamera.rect.width != viewportWidth || mainCamera.rect.height != viewportHeight) { mainCamera.rect = r; } float maxWidth = Mathf.Min( 1.0f - r.x, r.width ); float maxHeight = Mathf.Min( 1.0f - r.y, r.height ); float rectOffsetX = sr.x * scale.x; float rectOffsetY = sr.y * scale.y; if (r.x < 0.0f) { rectOffsetX += -r.x * pixelWidth; maxWidth = (r.x + r.width); } if (r.y < 0.0f) { rectOffsetY += -r.y * pixelHeight; maxHeight = (r.y + r.height); } left += rectOffsetX; bottom += rectOffsetY; right = pixelWidth * maxWidth + offset.x + rectOffsetX; top = pixelHeight * maxHeight + offset.y + rectOffsetY; } else { mainCamera.rect = new Rect(0, 0, 1, 1); } _screenExtents.Set(left / scale.x, top / scale.y, (right - left) / scale.x, (bottom - top) / scale.y); float far = mainCamera.farClipPlane; float near = mainCamera.near; // set up externally used variables orthoSize = (top - bottom) / 2.0f; _scaledResolution = new Vector2((right - left) / scale.x, (top - bottom) / scale.y); _screenOffset = offset; // Additional half texel offset // Takes care of texture unit offset, if necessary. // should be off on all opengl platforms // and on on PC/D3D bool halfTexelOffset = false; halfTexelOffset = (Application.platform == RuntimePlatform.WindowsPlayer || Application.platform == RuntimePlatform.WindowsWebPlayer || Application.platform == RuntimePlatform.WindowsEditor); float halfTexelOffsetAmount = (halfTexelOffset)?1.0f:0.0f; float x = (2.0f) / (right - left) * scale.x; float y = (2.0f) / (top - bottom) * scale.y; float z = -2.0f / (far - near); float a = -(right + left + halfTexelOffsetAmount) / (right - left); float b = -(bottom + top - halfTexelOffsetAmount) / (top - bottom); float c = -(far + near) / (far - near); Matrix4x4 m = new Matrix4x4(); m[0,0] = x; m[0,1] = 0; m[0,2] = 0; m[0,3] = a; m[1,0] = 0; m[1,1] = y; m[1,2] = 0; m[1,3] = b; m[2,0] = 0; m[2,1] = 0; m[2,2] = z; m[2,3] = c; m[3,0] = 0; m[3,1] = 0; m[3,2] = 0; m[3,3] = 1; mainCamera.projectionMatrix = m; }
/// <summary> /// Updates the camera matrix to ensure 1:1 pixel mapping /// </summary> public void UpdateCameraMatrix() { inst = this; if (!mainCamera.orthographic) { // Must be orthographic Debug.LogError("tk2dCamera must be orthographic"); mainCamera.orthographic = true; } float pixelWidth = mainCamera.pixelWidth; float pixelHeight = mainCamera.pixelHeight; #if UNITY_EDITOR if (forceResolutionInEditor) { pixelWidth = forceResolution.x; pixelHeight = forceResolution.y; } #endif _targetResolution = new Vector2(pixelWidth, pixelHeight); // Find an override if necessary if (!enableResolutionOverrides) currentResolutionOverride = null; if (enableResolutionOverrides && (currentResolutionOverride == null || (currentResolutionOverride != null && (currentResolutionOverride.width != pixelWidth || currentResolutionOverride.height != pixelHeight)) )) { currentResolutionOverride = null; // find one if it matches the current resolution if (resolutionOverride != null) { foreach (var ovr in resolutionOverride) { if (ovr.Match((int)pixelWidth, (int)pixelHeight)) { currentResolutionOverride = ovr; break; } } } } Vector2 scale = new Vector2(1, 1); Vector2 offset = new Vector2(0, 0); float s = 0.0f; if (currentResolutionOverride != null) { switch (currentResolutionOverride.autoScaleMode) { case tk2dCameraResolutionOverride.AutoScaleMode.FitHeight: s = pixelHeight / nativeResolutionHeight; scale.Set(s, s); break; case tk2dCameraResolutionOverride.AutoScaleMode.FitWidth: s = pixelWidth / nativeResolutionWidth; scale.Set(s, s); break; case tk2dCameraResolutionOverride.AutoScaleMode.FitVisible: case tk2dCameraResolutionOverride.AutoScaleMode.PixelPerfectFit: float nativeAspect = (float)nativeResolutionWidth / nativeResolutionHeight; float currentAspect = pixelWidth / pixelHeight; if (currentAspect < nativeAspect) s = pixelWidth / nativeResolutionWidth; else s = pixelHeight / nativeResolutionHeight; if (currentResolutionOverride.autoScaleMode == tk2dCameraResolutionOverride.AutoScaleMode.PixelPerfectFit) { if (s > 1.0f) s = Mathf.Floor(s); // round number else s = Mathf.Pow(2, Mathf.Floor(Mathf.Log(s, 2))); // minimise only as power of two } scale.Set(s, s); break; case tk2dCameraResolutionOverride.AutoScaleMode.StretchToFit: scale.Set(pixelWidth / nativeResolutionWidth, pixelHeight / nativeResolutionHeight); break; default: case tk2dCameraResolutionOverride.AutoScaleMode.None: s = currentResolutionOverride.scale; scale.Set(s, s); break; } scale *= zoomScale; // no offset when ScaleToFit if (currentResolutionOverride.autoScaleMode != tk2dCameraResolutionOverride.AutoScaleMode.StretchToFit) { switch (currentResolutionOverride.fitMode) { case tk2dCameraResolutionOverride.FitMode.Center: offset = new Vector2(Mathf.Round((nativeResolutionWidth * scale.x - pixelWidth ) / 2.0f), Mathf.Round((nativeResolutionHeight * scale.y - pixelHeight) / 2.0f)); break; default: case tk2dCameraResolutionOverride.FitMode.Constant: offset = -currentResolutionOverride.offsetPixels; break; } } } float left = offset.x, bottom = offset.y; float right = pixelWidth + offset.x, top = pixelHeight + offset.y; _screenExtents.Set(left / scale.x, top / scale.y, (right - left) / scale.x, (bottom - top) / scale.y); float far = mainCamera.farClipPlane; float near = mainCamera.near; // set up externally used variables orthoSize = (top - bottom) / 2.0f; _scaledResolution = new Vector2(right / scale.x, top / scale.y); _screenOffset = offset; // Additional half texel offset // Takes care of texture unit offset, if necessary. // should be off on all opengl platforms // and on on PC/D3D bool halfTexelOffset = false; halfTexelOffset = (Application.platform == RuntimePlatform.WindowsPlayer || Application.platform == RuntimePlatform.WindowsWebPlayer || Application.platform == RuntimePlatform.WindowsEditor); float halfTexelOffsetAmount = (halfTexelOffset)?1.0f:0.0f; float x = (2.0f) / (right - left) * scale.x; float y = (2.0f) / (top - bottom) * scale.y; float z = -2.0f / (far - near); float a = -(right + left + halfTexelOffsetAmount) / (right - left); float b = -(bottom + top - halfTexelOffsetAmount) / (top - bottom); float c = -(far + near) / (far - near); Matrix4x4 m = new Matrix4x4(); m[0,0] = x; m[0,1] = 0; m[0,2] = 0; m[0,3] = a; m[1,0] = 0; m[1,1] = y; m[1,2] = 0; m[1,3] = b; m[2,0] = 0; m[2,1] = 0; m[2,2] = z; m[2,3] = c; m[3,0] = 0; m[3,1] = 0; m[3,2] = 0; m[3,3] = 1; mainCamera.projectionMatrix = m; }
public override void Run () { float horizontalAxis = Input.GetAxisRaw ("Horizontal"); float verticalAxis = Input.GetAxisRaw ("Vertical"); Vector2 dir = new Vector2 (entity.leftOrRight, 0); if (horizontalAxis > 0) { entity.MoveRight(); } else if (horizontalAxis < 0) { entity.MoveLeft(); } dir.Set (entity.leftOrRight, 0); if (verticalAxis < 0) { if (horizontalAxis != 0) { //Moving horizontally dir.y = -1; } else if (!bill.onFloor && !bill.inWater) { dir.Set (0, -1); } else { entity.Crouch(); } if(bill.inWater){ entity.Crouch(); } } else { entity.Uncrouch(); } if (verticalAxis > 0) { if (horizontalAxis != 0) { dir.y = 1; } else { dir.Set (0, 1); } } if (Input.GetKeyDown (jumpKey) ){ //entity.Jump(); bill.Jump (horizontalAxis); } if (Input.GetKeyDown (shootKey)) { // shoot logic //Debug.Log("Shoot!"); entity.Shoot(); } else if (Input.GetKey (shootKey)) { //Debug.Log("If i have an MGun, continuously shoot!"); if(bill.gun.GetType().ToString() == "MGun"){ entity.Shoot(); } } if (Input.GetKeyDown (invincibleKey)) { bill.godMode = !bill.godMode; } if (bill.isCrouched) { dir.y = 0; } entity.dir = dir; }
// Update is called once per frame void Update() { paddlePos.Set(GetScreenUnitX(), transform.position.y); paddlePos.x = Mathf.Clamp(paddlePos.x, 0, (screenUnitWidth - spriteUnitWidth)); transform.position = paddlePos; }
public Dominos() { Body b1; { var shape = new EdgeShape(); shape.SetTwoSided(new Vector2(-40.0f, 0.0f), new Vector2(40.0f, 0.0f)); var bd = new BodyDef(); b1 = World.CreateBody(bd); b1.CreateFixture(shape, 0.0f); } { var shape = new PolygonShape(); shape.SetAsBox(6.0f, 0.25f); var bd = new BodyDef(); bd.Position.Set(-1.5f, 10.0f); var ground = World.CreateBody(bd); ground.CreateFixture(shape, 0.0f); } { var shape = new PolygonShape(); shape.SetAsBox(0.1f, 1.0f); var fd = new FixtureDef(); fd.Shape = shape; fd.Density = 20.0f; fd.Friction = 0.1f; for (var i = 0; i < 10; ++i) { var bd = new BodyDef(); bd.BodyType = BodyType.DynamicBody; bd.Position.Set(-6.0f + 1.0f * i, 11.25f); var body = World.CreateBody(bd); body.CreateFixture(fd); } } { var shape = new PolygonShape(); shape.SetAsBox(7.0f, 0.25f, Vector2.Zero, 0.3f); var bd = new BodyDef(); bd.Position.Set(1.0f, 6.0f); var ground = World.CreateBody(bd); ground.CreateFixture(shape, 0.0f); } Body b2; { var shape = new PolygonShape(); shape.SetAsBox(0.25f, 1.5f); var bd = new BodyDef(); bd.Position.Set(-7.0f, 4.0f); b2 = World.CreateBody(bd); b2.CreateFixture(shape, 0.0f); } Body b3; { var shape = new PolygonShape(); shape.SetAsBox(6.0f, 0.125f); var bd = new BodyDef(); bd.BodyType = BodyType.DynamicBody; bd.Position.Set(-0.9f, 1.0f); bd.Angle = -0.15f; b3 = World.CreateBody(bd); b3.CreateFixture(shape, 10.0f); } var jd = new RevoluteJointDef(); var anchor = new Vector2(); anchor.Set(-2.0f, 1.0f); jd.Initialize(b1, b3, anchor); jd.CollideConnected = true; World.CreateJoint(jd); Body b4; { var shape = new PolygonShape(); shape.SetAsBox(0.25f, 0.25f); var bd = new BodyDef(); bd.BodyType = BodyType.DynamicBody; bd.Position.Set(-10.0f, 15.0f); b4 = World.CreateBody(bd); b4.CreateFixture(shape, 10.0f); } anchor.Set(-7.0f, 15.0f); jd.Initialize(b2, b4, anchor); World.CreateJoint(jd); Body b5; { var bd = new BodyDef(); bd.BodyType = BodyType.DynamicBody; bd.Position.Set(6.5f, 3.0f); b5 = World.CreateBody(bd); var shape = new PolygonShape(); var fd = new FixtureDef(); fd.Shape = shape; fd.Density = 10.0f; fd.Friction = 0.1f; shape.SetAsBox(1.0f, 0.1f, new Vector2(0.0f, -0.9f), 0.0f); b5.CreateFixture(fd); shape.SetAsBox(0.1f, 1.0f, new Vector2(-0.9f, 0.0f), 0.0f); b5.CreateFixture(fd); shape.SetAsBox(0.1f, 1.0f, new Vector2(0.9f, 0.0f), 0.0f); b5.CreateFixture(fd); } anchor.Set(6.0f, 2.0f); jd.Initialize(b1, b5, anchor); World.CreateJoint(jd); Body b6; { var shape = new PolygonShape(); shape.SetAsBox(1.0f, 0.1f); var bd = new BodyDef(); bd.BodyType = BodyType.DynamicBody; bd.Position.Set(6.5f, 4.1f); b6 = World.CreateBody(bd); b6.CreateFixture(shape, 30.0f); } anchor.Set(7.5f, 4.0f); jd.Initialize(b5, b6, anchor); World.CreateJoint(jd); Body b7; { var shape = new PolygonShape(); shape.SetAsBox(0.1f, 1.0f); var bd = new BodyDef(); bd.BodyType = BodyType.DynamicBody; bd.Position.Set(7.4f, 1.0f); b7 = World.CreateBody(bd); b7.CreateFixture(shape, 10.0f); } var djd = new DistanceJointDef(); djd.BodyA = b3; djd.BodyB = b7; djd.LocalAnchorA.Set(6.0f, 0.0f); djd.LocalAnchorB.Set(0.0f, -1.0f); var d = djd.BodyB.GetWorldPoint(djd.LocalAnchorB) - djd.BodyA.GetWorldPoint(djd.LocalAnchorA); djd.Length = d.Length(); World.CreateJoint(djd); { var radius = 0.2f; var shape = new CircleShape(); shape.Radius = radius; for (var i = 0; i < 4; ++i) { var bd = new BodyDef(); bd.BodyType = BodyType.DynamicBody; bd.Position.Set(5.9f + 2.0f * radius * i, 2.4f); var body = World.CreateBody(bd); body.CreateFixture(shape, 10.0f); } } }
void Update() { #if UNITY_EDITOR if (Input.GetMouseButton(0)) { currentPosition = currentCamera.ScreenToWorldPoint(Input.mousePosition) - transform.position; if (previousPosition == Vector2.zero) { previousPosition = currentPosition; } float _angle = (Mathf.Atan2(currentPosition.y, currentPosition.x) - Mathf.Atan2(previousPosition.y, previousPosition.x)) * Mathf.Rad2Deg; previousPosition = currentPosition; if (_angle == 0 && crankSource.isPlaying) { if (crankSource.isPlaying) { crankSource.Pause(); } return; } else if (!crankSource.isPlaying) { crankSource.UnPause(); } transform.eulerAngles += new Vector3(0, 0, _angle); _angle = Mathf.Clamp(_angle, -1, 1); thermometer.IncreaseRatio(Mathf.Abs(_angle * Time.deltaTime)); } else { if (crankSource.isPlaying) { crankSource.Pause(); } previousPosition.Set(0, 0); } #else if (Input.touchCount == 1) { currentPosition = currentCamera.ScreenToWorldPoint(Input.GetTouch(0).position) - transform.position; if (previousPosition == Vector2.zero) { previousPosition = currentPosition; } float _angle = (Mathf.Atan2(currentPosition.y, currentPosition.x) - Mathf.Atan2(previousPosition.y, previousPosition.x)) * Mathf.Rad2Deg; previousPosition = currentPosition; if (_angle == 0 && crankSource.isPlaying) { if (crankSource.isPlaying) { crankSource.Pause(); } return; } else if (!crankSource.isPlaying) { crankSource.UnPause(); } transform.eulerAngles += new Vector3(0, 0, _angle); _angle = Mathf.Clamp(_angle, -1, 1); thermometer.IncreaseRatio(Mathf.Abs(_angle * Time.deltaTime)); } else { if (crankSource.isPlaying) { crankSource.Pause(); } previousPosition.Set(0, 0); } #endif }
public void Start() { init(); int i,j; Vector2 position = new Vector2(); Quaternion rotation = new Quaternion(); for ( i = 0; i < map1.GetLength(0); i++) { for ( j = 0; j < map1.GetLength(1); j++) { position.Set(0.5f + j, 0.5f - i); switch (map1[i, j]) { case 0: objMap[i,j]=Instantiate(wall, position, rotation)as GameObject; objMap[i,j].SetActive(false); break; case 1: objMap[i,j]=Instantiate(tile, position, rotation)as GameObject; objMap[i,j].SetActive(false); break; case 2: if (i>0 && i<map1.GetLength(0)-1 && map1[i - 1, j] == 0 && map1[i + 1, j] == 0) objMap[i,j]=Instantiate(door2, position, rotation)as GameObject; if (j>0 && j<map1.GetLength(1)-1 && map1[i, j - 1] == 0 && map1[i, j + 1] == 0) objMap[i,j]=Instantiate(door1, position, rotation)as GameObject; objMap[i,j].SetActive(false); break; case 3: objMap[i,j] =Instantiate(water, position, rotation)as GameObject; objMap[i,j].SetActive(false); break; case 4: objMap[i,j]=Instantiate(crossroads, position, rotation)as GameObject; objMap[i,j].SetActive(false); break; case 5: objMap[i,j]=Instantiate(lava, position, rotation)as GameObject; objMap[i,j].SetActive(false); break; case 6: objMap[i,j]=Instantiate(hole, position, rotation)as GameObject; objMap[i,j].SetActive(false); break; case 7: objMap[i,j]=Instantiate(fog, position, rotation)as GameObject; objMap[i,j].SetActive(false); break; case 8: objMap[i,j]=Instantiate(safe, position, rotation)as GameObject; objMap[i,j].SetActive(false); break; case 9: objMap[i,j]=Instantiate(teleport, position, rotation)as GameObject; objMap[i,j].tag=whichMap+""; objMap[i,j].AddComponent<TeleportScript>(); objMap[i,j].SetActive(false); break; case 12: if (map1[i - 1, j] == 0 || map1[i + 1, j] == 0) objMap[i,j] = Instantiate(stairv, position, rotation) as GameObject; else if (map1[i, j - 1] == 0 || map1[i, j + 1] == 0) objMap[i,j] = Instantiate(stairh, position, rotation) as GameObject; objMap[i,j].gameObject.tag = whichMap+"Down"; objMap[i,j].AddComponent<SwitchLevels>(); objMap[i,j].SetActive(false); break; case 21: if (map1[i - 1, j] == 0 || map1[i + 1, j] == 0) objMap[i,j] = Instantiate(stairv, position, rotation) as GameObject; else if (map1[i, j - 1] == 0 || map1[i, j + 1] == 0) objMap[i,j]= Instantiate(stairh, position, rotation) as GameObject; objMap[i,j].gameObject.tag = whichMap+"Up"; objMap[i,j].AddComponent<SwitchLevels>(); objMap[i,j].SetActive(false); break; } } } //getting player position to set surrounding tiles visible playerX=(int)PlayerPrefs.GetFloat("PlayX"); playerY=(int)Mathf.Abs(PlayerPrefs.GetFloat("PlayY"))+1; Debug.Log("player: "+playerX+" , "+playerY); si=playerX-sight; sj=playerY-sight; ti=playerX+sight; tj=playerY+sight; Debug.Log("lines: "+si+" , "+ti); Debug.Log("lines: "+sj+" , "+tj); for (i=si;i<=ti;i++) for(j=sj;j<=tj;j++) if (i>=0 && i<=44 && j>=0 && j<=34 && !objMap[i,j].activeSelf) //if (j>0 && map1[i,j-1]==0); //else objMap[i,j].SetActive(true); }