private Quaternion rotationTowardsHive() { Vector3 direction = (hive.transform.position - transform.position).normalized; float angle = Mathf.Atan2(direction.y, direction.x) * Mathf.Rad2Deg; return(Quaternion.AngleAxis(angle, Vector3.forward)); }
private void Rotate() { Vector2 dir = GameObject.Find("dot (1)").transform.position - transform.parent.position; float angle = Mathf.Atan2(dir.y, dir.x) * Mathf.Rad2Deg; transform.parent.rotation = Quaternion.AngleAxis(angle, Vector3.forward); }
private void CorrectRotation() { Vector2 direction = Target.transform.position - transform.position; float angle = Mathf.Atan2(direction.y, direction.x) * Mathf.Rad2Deg; transform.rotation = Quaternion.AngleAxis(angle, Vector3.forward); }
protected void RotateSlice(List <GameObject> slice, float angleInDeg) { Vector3 axis = (m_shuffleCoroutine != null || m_solveCoroutine != null) ? transform.TransformVector(m_selectedPlane .normal) : m_selectedPlane .normal; Vector3 point = m_selectedPlane.distance * axis; for (int i = 0; i < slice.Count; i++) { Vector3 position = slice[i].transform.position; slice[i].transform.position = point + Quaternion.AngleAxis(angleInDeg, axis) * (position - point); slice[i].transform.rotation = Quaternion.AngleAxis(angleInDeg, axis) * slice[i].transform.rotation; } Vector3 up = Mathf.Abs(Vector3.Dot(slice.Last().transform.up, axis)) < 0.5f ? slice.Last().transform.up : Mathf.Abs(Vector3.Dot(slice.Last().transform.right, axis)) < 0.5f ? slice.Last().transform.right : slice.Last().transform.forward; m_NeutralPlaneSlice1.transform.rotation = Quaternion.LookRotation(-axis, up); m_NeutralPlaneSlice2.transform.rotation = Quaternion.LookRotation(axis, up); }
void LateUpdate() { /*Vector3 targetPosition = target.TransformPoint(new Vector3(0, 1, -3)); * * transform.position = Vector3.SmoothDamp(transform.position, targetPosition, ref velocity, smoothTime); * * transform.LookAt(target);*/ if (RotateAroundTarget) { Quaternion camTurnAngle = Quaternion.AngleAxis(Input.GetAxis("Mouse X") * RotationSpeed, Vector3.up); cameraOffset = camTurnAngle * cameraOffset; } Vector3 newPos = targetTransform.position + cameraOffset; //transform.position = Vector3.Slerp(transform.position, newPos, smoothFactor); transform.position = Vector3.SmoothDamp(transform.position, newPos, ref velocity, smoothTime); if (LookAtTarget || RotateAroundTarget) { transform.LookAt(targetTransform); } }
protected IEnumerator InfinitRotateCoroutine(Vector3 axis, float rotationSpeedInDeg) { do { transform.rotation = Quaternion.AngleAxis(rotationSpeedInDeg * Time.deltaTime, axis) * transform.rotation; yield return(null); } while (true); }
/// <summary> /// Converts IMU rotation from the gyroscope to XYZ Tait-Bryan angles. /// </summary> /// <param name="imuAngles">The rotion from the gyroscope in degrees</param> /// <returns></returns> public static Vector3 IMUToXYZ(Vector3 imuAngles) { Quaternion res = Quaternion.AngleAxis(imuAngles.x, Vector3.right); res = res * Quaternion.AngleAxis(imuAngles.y, res * Vector3.up); res = res * Quaternion.AngleAxis(imuAngles.z, res * Vector3.forward); return(ZXYtoXYZ(res.eulerAngles)); }
private void OnLowerBodyAnglesChanged(HumanoidAngles <Vector3> absoluteAngles) { var headsetRotation = Quaternion.identity; var initialWaistYaw = WaistBaseOrientation.z; var initialWaistAngles = Quaternion.AngleAxis(initialWaistYaw, Vector3.up); _yawAdjustedWaistAngles[0] = absoluteAngles.Waist.x; _yawAdjustedWaistAngles[1] = absoluteAngles.Waist.y; _yawAdjustedWaistAngles[2] = absoluteAngles.Waist.z; _yawAdjustedLeftUpperLegAngles[0] = absoluteAngles.LeftUpperLeg.x; _yawAdjustedLeftUpperLegAngles[1] = absoluteAngles.LeftUpperLeg.y; _yawAdjustedLeftUpperLegAngles[2] = absoluteAngles.LeftUpperLeg.z; _yawAdjustedLeftLowerLegAngles[0] = absoluteAngles.LeftLowerLeg.x; _yawAdjustedLeftLowerLegAngles[1] = absoluteAngles.LeftLowerLeg.y; _yawAdjustedLeftLowerLegAngles[2] = absoluteAngles.LeftLowerLeg.z; _yawAdjustedRightUpperLegAngles[0] = absoluteAngles.RightUpperLeg.x; _yawAdjustedRightUpperLegAngles[1] = absoluteAngles.RightUpperLeg.y; _yawAdjustedRightUpperLegAngles[2] = absoluteAngles.RightUpperLeg.z; _yawAdjustedRightLowerLegAngles[0] = absoluteAngles.RightLowerLeg.x; _yawAdjustedRightLowerLegAngles[1] = absoluteAngles.RightLowerLeg.y; _yawAdjustedRightLowerLegAngles[2] = absoluteAngles.RightLowerLeg.z; // Transform absolute lower body angles into relative ones var localAngleWaist = _jointRotations.rotateWaist( _yawAdjustedWaistAngles, initialWaistAngles, headsetRotation ); var localAngleLeftUpperLeg = _jointRotations.rotateLeftLeg( _yawAdjustedLeftUpperLegAngles, localAngleWaist, initialWaistAngles ); var localAngleLeftLowerLeg = _jointRotations.rotateLeftShin( _yawAdjustedLeftLowerLegAngles, localAngleWaist, localAngleLeftUpperLeg, initialWaistAngles ); var localAngleRightUpperLeg = _jointRotations.rotateRightLeg( _yawAdjustedRightUpperLegAngles, localAngleWaist, initialWaistAngles ); var localAngleRightLowerLeg = _jointRotations.rotateRightShin( _yawAdjustedRightLowerLegAngles, localAngleWaist, localAngleRightUpperLeg, initialWaistAngles ); LocalAngles.SetLowerBodyAngles(localAngleWaist, localAngleLeftUpperLeg, localAngleLeftLowerLeg, localAngleRightUpperLeg, localAngleRightLowerLeg); }
private Quaternion GetSplashSpawnRot(Transform parentProjectileTransform, float angle) { float yOffsetAngle = Random.Range(-splashMaxYOffset, splashMaxYOffset); Quaternion yRot = Quaternion.AngleAxis(yOffsetAngle, parentProjectileTransform.forward); Quaternion xzRot = Quaternion.AngleAxis(angle, parentProjectileTransform.up); return(yRot * xzRot); }
void RotateToTarget(Vector3 pos) { Vector3 vectorToTarget = pos - transform.position; float angle = Mathf.Atan2(vectorToTarget.y, vectorToTarget.x) * Mathf.Rad2Deg; Quaternion q = Quaternion.AngleAxis(angle, Vector3.forward) * Quaternion.Euler(offset); transform.rotation = Quaternion.Slerp(transform.rotation, q, Time.deltaTime * 10); }
private void BuildTowerFirstLevel(List <Transform> openList, Vector3 pos, int currentFloor, float doorWeight, float wallWeight) { //build the walls and make sure there is at least 2 doors float currentDoorWeight = doorWeight; float currentWallWeight = wallWeight; int doorsQuantity = 0; for (int i = 0; i < 6; i++) { RaycastHit hit; //checks for link and build a bridge if there is if (Physics.Raycast(pos + Vector3.up * currentFloor * _heightFloor + Vector3.up * 4.0f, Quaternion.AngleAxis((i * 60) + 180, Vector3.up) * Vector3.forward, out hit, maxDistanceRayCastLink, linkLayer)) { if (hit.transform.CompareTag("Link")) { InstantiateDoor(pos, currentFloor, i); currentDoorWeight -= doorWeight / (maxDoorsPerFloor); doorsQuantity++; } } //checks for no link (wall/window) and builds a no link if there is else if (Physics.Raycast(pos + Vector3.up * currentFloor * _heightFloor + Vector3.up * 4.0f, Quaternion.AngleAxis((i * 60) + 180, Vector3.up) * Vector3.forward, out hit, maxDistanceRayCastLink, notLinkLayer)) { if (hit.transform.CompareTag("NotLink")) { InstantiateWall(pos, currentFloor, i); currentWallWeight -= wallWeight / (6 - minDoorsPerFloor); } } else { if (Random.Range(0.0f, 1.0f) * currentDoorWeight > Random.Range(0.0f, 1.0f) * currentWallWeight) { GameObject door = InstantiateDoor(pos, currentFloor, i); openList.Add(door.transform); currentDoorWeight -= doorWeight / (maxDoorsPerFloor); doorsQuantity++; } else { InstantiateWall(pos, currentFloor, i); currentWallWeight -= wallWeight / (6 - minDoorsPerFloor); } } } if (doorsQuantity < minDoorsPerFloor) { _specialRooms.Add(pos); } }
private void InterpolateRotationData(float currentTime) { var currentInterpolationTime = currentTime - timeDifferentialToRotationSender - SimulationSettings.OtherPlayerUpdateDelay; if (ReadyToInterpolate(ref rotationInterpolationRoot, ref rotationUpdates, currentInterpolationTime)) { var interpolationTarget = rotationUpdates.Peek(); var lerpRate = (currentInterpolationTime - rotationInterpolationRoot.timestamp) / (interpolationTarget.timestamp - rotationInterpolationRoot.timestamp); playerRigidbody.MoveRotation(Quaternion.Slerp(Quaternion.AngleAxis(rotationInterpolationRoot.data, Vector3.up), Quaternion.AngleAxis(interpolationTarget.data, Vector3.up), lerpRate)); } }
void DoSwingAction() { // Calculate angle between player and tether point and rotate the player around it var dir = (tetherTransform.position - transform.position); var angle = Mathf.Atan2(dir.y, dir.x) * Mathf.Rad2Deg; transform.rotation = Quaternion.AngleAxis(angle - 90, Vector3.forward); // Fire Rope (Extra check, every thing here runs only once per tethering action) if (Input.GetMouseButtonDown(0)) { // Get the vector to the closest Tether point as long as there are points closestTether = FindClosestTetherPoint(gos).transform.position - transform.position; // Move pressed indicator position to tetherTransform pos indicatorGameObject.transform.position = new Vector3(tetherTransform.position.x, tetherTransform.position.y + indicatorPressedOffset, 0); indicatorSphere.transform.position = new Vector3(tetherTransform.position.x, tetherTransform.position.y, 0); // Shoot a ray out towards that position LayerMask ignorePlayer = ~(1 << LayerMask.NameToLayer("Player")); Physics.Raycast(transform.position, closestTether, out RaycastHit hit, maxTetherDistance, ignorePlayer); if (hit.collider) { if (hit.collider.tag == "Tether Points") { // Move the anchor to the correct position anchor.transform.position = new Vector3(hit.point.x, hit.point.y, 0); // Zero out any rotation of anchor anchor.transform.rotation = Quaternion.identity; // Create HingeJoints joint = gameObject.AddComponent <HingeJoint>(); joint.axis = Vector3.forward; joint.anchor = Vector3.zero; joint.connectedBody = anchor.GetComponent <Rigidbody>(); // Create anchor HingeJoint anchorJoint = anchor.AddComponent <HingeJoint>(); anchorJoint.axis = Vector3.forward; anchorJoint.anchor = Vector3.zero; lr.enabled = true; // show rope // Play connect sound if (!soundplayed) { connectSound.Play(0); soundplayed = true; } } } } }
private Quaternion RotateAroundAxis(Vector3 pointA, Vector3 pointB, Quaternion startRotation) { Vector3 direction3d = pointA - pointB; float angle = Mathf.Atan2(direction3d.z, direction3d.x) * Mathf.Rad2Deg; Quaternion rotateAround = Quaternion.AngleAxis(angle, Vector3.forward); Quaternion rotation = Quaternion.Euler(rotateAround.eulerAngles); Debug.Log(rotateAround.eulerAngles); return(rotation); }
private void UpdateAimGuide() { var yaw = Quaternion.AngleAxis(_yaw, Vector3.up); var pitch = Quaternion.Euler(_pitch, 0f, 0f); var angle = yaw * pitch; var distance = (Vector3.forward * 2f); if (_aimGuide == null) { _aimGuide = Instantiate(aimGuidePrefab, transform.position + (Vector3.forward * 2f), Quaternion.identity); } _aimGuide.transform.position = transform.position + angle * distance; _aimGuide.transform.rotation = angle * Quaternion.Euler(90f, 0f, 0f); }
private void Update() { if (currentHoldingObject) { currentHoldingObject.transform.position = holdingPoint.position; } //Move in Direction transform.position += new Vector3(direction.x, direction.y, 0) * speed; //Rotate in Direction RotateToTarget(new Vector3(direction.x, direction.y, 0)); wanderingTimer += Time.deltaTime; if (wanderingTimer >= wanderingDirectionChange) { if (currentState == State.SearchingFood) { direction = Vector3.Normalize( Quaternion.AngleAxis(Random.Range(-angleDirectionRange, angleDirectionRange), Vector3.forward) * direction); } wanderingTimer = 0; } spawnItemTimer += Time.deltaTime; if (spawnItemTimer >= spawnItemInterval) { switch (currentState) { case State.GoingHome: GameObject foodP = Instantiate(foodPheromone, transform.position, Quaternion.identity); foodP.GetComponent <ItemType>().direction = DirectionToPosition(transform.position, previousFoodPheromonePosition); previousFoodPheromonePosition = foodP.transform.position; break; case State.SearchingFood: GameObject homeP = Instantiate(homePheromone, transform.position, Quaternion.identity); homeP.GetComponent <ItemType>().direction = DirectionToPosition(transform.position, previousHomePheromonePosition); previousHomePheromonePosition = homeP.transform.position; break; } spawnItemTimer = 0; } }
private Vector3 AvoidWalls(Vector3 direction) { if (Time.time > previousTime + disableRayDuration && isRayDisabled) { isRayDisabled = false; } if (isRayDisabled) { return(leftWallHit.normal + rightWallHit.normal + new Vector2(direction.x, direction.y).normalized); } hasHitLeft = hasHitRight = false; var leftRayDirection = Quaternion.AngleAxis(-detectionAngle, Vector3.forward) * heading; var rightRayDirection = Quaternion.AngleAxis(detectionAngle, Vector3.forward) * heading; Debug.DrawRay(transform.position, leftRayDirection * raycastLength, Color.green); Debug.DrawRay(transform.position, rightRayDirection * raycastLength, Color.green); var origin = new Vector2(transform.position.x, transform.position.y); var leftRay = new Vector2(leftRayDirection.x, leftRayDirection.y); var rightRay = new Vector2(rightRayDirection.x, rightRayDirection.y); leftWallHit = Physics2D.Raycast(origin, leftRay, raycastLength, LayerMask.GetMask("Wall")); rightWallHit = Physics2D.Raycast(origin, rightRay, raycastLength, LayerMask.GetMask("Wall")); hasHitLeft = leftWallHit.collider != null; hasHitRight = rightWallHit.collider != null; if (hasHitLeft && hasHitRight) { isRayDisabled = true; previousTime = Time.time; } if (hasHitLeft) { direction = leftWallHit.normal; } if (hasHitRight) { direction = rightWallHit.normal; } return(direction); }
protected virtual void _updateIntegration(float dt, ref Vector3 pos, ref Quaternion rot, Vector3 vel, Vector3 avel) { pos += vel * dt; Vector3 vector3 = avel; float num1 = vector3.magnitude; if (num1 <= 0.0000001) { return; } Quaternion quaternion = Quaternion.AngleAxis(dt * num1 * Mathf.Rad2Deg, vector3 * (1f / num1)); quaternion.Normalize(); rot = quaternion * rot; rot.Normalize(); }
void LateUpdate() { var scroll = Input.GetAxis("Mouse ScrollWheel"); offset = Quaternion.AngleAxis(Input.GetAxis("Horizontal") * TURN_SPEED, Vector3.up) * Quaternion.AngleAxis(Input.GetAxis("Vertical") * TURN_SPEED, Vector3.right) * offset; transform.position = player.position + offset; var fieldOfView = camera.fieldOfView; fieldOfView = fieldOfView <FOV_MIN?FOV_MIN : fieldOfView> FOV_MAX ? FOV_MAX : fieldOfView - scroll * SPEED; camera.fieldOfView = fieldOfView; transform.LookAt(player.position); }
// Update is called once per frame void Update() { bool willmove = !lookOnRightClick || Input.GetMouseButton(1); if (willmove) { Vector2 mouseDelta = new Vector2(Input.GetAxis("Mouse X"), Input.GetAxis("Mouse Y")); mouseDelta = Vector2.Scale(mouseDelta, new Vector2(sensitivity * smoothing, sensitivity * smoothing)); // the interpolated float result between the two float values smoothV.x = Mathf.Lerp(smoothV.x, mouseDelta.x, 1f / smoothing); smoothV.y = Mathf.Lerp(smoothV.y, mouseDelta.y, 1f / smoothing); mouseLook += smoothV; transform.localRotation = Quaternion.AngleAxis(-mouseLook.y, Vector3.right); character.transform.localRotation = Quaternion.AngleAxis(mouseLook.x, character.transform.up); } }
private void Spawn() { var angle = Random.Range(0, 360); var spawnPosition = GetSpawnPosition(angle); var asteroidRotation = Random.Range(0, 360); var id = Random.Range(0, AsteroidPrefabs.Count - 1); var asteroid = Instantiate(AsteroidPrefabs[id], spawnPosition, Quaternion.AngleAxis(asteroidRotation, Vector3.forward)); var size = Random.Range(AsteroidSizeMin, AsteroidSizeMax); asteroid.transform.localScale = Vector3.one * size; var asteroidRb = asteroid.GetComponent <Rigidbody2D>(); var asteroidSpeed = Random.Range(AsteroidSpeedMin, AsteroidSpeedMax); asteroidRb.velocity = GetAsteroidVelocity(angle) * asteroidSpeed; }
// Update is called once per frame void Update() { //check if the mouse is held down if (Input.GetMouseButton(0)) { //transform the mouse position to game coordinates Vector2 mPos = Input.mousePosition; Vector3 wPos = Camera.main.ScreenToWorldPoint(new Vector3(mPos.x, mPos.y, transform.position.z)); wPos.z = transform.position.z; //get the relative direction var dir = wPos - transform.position; dir.Normalize(); //accelerate towards the direction m_speed += dir * Acceleration * Time.deltaTime; //assemble the quaternion for the new rotation float angle = Mathf.Atan2(dir.y, dir.x) * Mathf.Rad2Deg; Quaternion rotation = Quaternion.AngleAxis(angle, Vector3.forward); //rotate towards the look-direction transform.rotation = Quaternion.Slerp(transform.rotation, rotation, Time.deltaTime * RotationSpeed); } //check if the speed is above our epsilon value and apply drag if it is if (Math.Abs(m_speed.y) >= MIN_EPSILON || Math.Abs(m_speed.x) >= MIN_EPSILON) { m_speed *= Drag; } else { //below a certain epsilon simply set the speed to 0 m_speed = Vector3.zero; } //do euler step transform.position += m_speed * Time.deltaTime; }
// Angled bullets pattern IEnumerator ShootBullets() { for (int i = 0; i < 8; i++) { _angle += 5f; Quaternion rotation = Quaternion.AngleAxis(_angle, transform.forward) * transform.rotation; Instantiate(_octoBulletPrefab, _firePoint.position, rotation); _sources[0].Play(); yield return(new WaitForSeconds(0.1f)); } yield return(new WaitForSeconds(0.8f)); for (int i = 0; i < 8; i++) { _angle -= 5f; Quaternion rotation = Quaternion.AngleAxis(_angle, transform.forward) * transform.rotation; Instantiate(_octoBulletPrefab, _firePoint.position, rotation); _sources[0].Play(); yield return(new WaitForSeconds(0.1f)); } }
private static void DrawFreeLookGizmos(CinemachineFreeLook vcam, GizmoType selectionType) { // Standard frustum and logo CinemachineBrainEditor.DrawVirtualCameraBaseGizmos(vcam, selectionType); Color originalGizmoColour = Gizmos.color; bool isActiveVirtualCam = CinemachineCore.Instance.IsLive(vcam); Gizmos.color = isActiveVirtualCam ? CinemachineSettings.CinemachineCoreSettings.ActiveGizmoColour : CinemachineSettings.CinemachineCoreSettings.InactiveGizmoColour; if (vcam.Follow != null) { Vector3 pos = vcam.Follow.position; Vector3 up = vcam.State.ReferenceUp; var MiddleRig = vcam.GetRig(1).GetCinemachineComponent <CinemachineOrbitalTransposer>(); if (MiddleRig != null) { Quaternion orient = MiddleRig.GetReferenceOrientation(up); up = orient * Vector3.up; float rotation = vcam.m_XAxis.Value + vcam.m_Heading.m_Bias; orient = Quaternion.AngleAxis(rotation, up) * orient; CinemachineOrbitalTransposerEditor.DrawCircleAtPointWithRadius( pos + up * vcam.m_Orbits[0].m_Height, orient, vcam.m_Orbits[0].m_Radius); CinemachineOrbitalTransposerEditor.DrawCircleAtPointWithRadius( pos + up * vcam.m_Orbits[1].m_Height, orient, vcam.m_Orbits[1].m_Radius); CinemachineOrbitalTransposerEditor.DrawCircleAtPointWithRadius( pos + up * vcam.m_Orbits[2].m_Height, orient, vcam.m_Orbits[2].m_Radius); DrawCameraPath(pos, orient, vcam); } } Gizmos.color = originalGizmoColour; }
public override void Draw() { base.Draw(); var delta = End - Position; float len = delta.magnitude; var dir = delta.normalized; float angSin = Mathf.Sin(Mathf.Deg2Rad * Angle); float radius = angSin * len; Handles.color = Color; var perp2d = Vector2.Perpendicular(new Vector2(dir.x, dir.z)); var perpendicular = Vector3.Cross(dir, new Vector3(perp2d.x, 0, perp2d.y)).normalized; var start = Quaternion.AngleAxis(-Angle * 0.5f, perpendicular) * dir; var end = Quaternion.AngleAxis(Angle * 0.5f, perpendicular) * dir; Handles.DrawWireArc(Position, perpendicular, start, Angle, len); Handles.DrawLine(Position, Position + start * len); Handles.DrawLine(Position, Position + end * len); }
static public void Test() { UQuaternion q1 = new UQuaternion(.1f, .2f, .3f, -4); UQuaternion q2 = new UQuaternion(10, 9, -8, 7); Debug.Assert(q1.Equals(ToUnity(FromUnity(q1)))); Debug.Assert(q2.Equals(ToUnity(FromUnity(q2)))); Debug.Assert(q1.normalized.EqTest(ToUnity(FromUnity(q1).normalized))); Debug.Assert(q2.normalized.EqTest(ToUnity(FromUnity(q2).normalized))); q1.Normalize(); // Unity's inverse method only works for normalized q2.Normalize(); // Quaternions. Debug.Assert(UQuaternion.Inverse(q1).Equals(ToUnity(Inverse(FromUnity(q1))))); Debug.Assert(UQuaternion.Inverse(q2).EqTest(ToUnity(Inverse(FromUnity(q2))))); Debug.Assert((q1 * q2).Equals(ToUnity(FromUnity(q1 * q2)))); Debug.Assert((q2 * q1).Equals(ToUnity(FromUnity(q2 * q1)))); Vector3 axis; DVector3 daxis; float angle; axis = new Vector3(1, 2, 3); daxis = DVector3.FromUnity(axis); angle = 27; Debug.Assert(UQuaternion.AngleAxis(angle, axis).EqTest(ToUnity(DQuaternion.AngleAxis(angle, daxis)))); axis = new Vector3(-1, 2, -.1f); daxis = DVector3.FromUnity(axis); angle = -500; Debug.Assert(UQuaternion.AngleAxis(angle, axis).EqTest(ToUnity(DQuaternion.AngleAxis(angle, daxis)))); }
public void StatusStep() { if (World.worldInstance == null) { return; } // Make sure we are mature enough if (entity.currentAge < entity.typeInfo.matureAge * 0.7f) { return; } // If we didn't hit our seed probability, then just skip this update if (UnityEngine.Random.value >= seedProbability) { return; } // Choose random position around the plant var minRadius = Mathf.Min(tooCloseToGrowAnyType, tooCloseToGrowSameType); var maxRadius = Mathf.Max(tooCloseToGrowAnyType, tooCloseToGrowSameType); Vector3 offset = new Vector3(1, 0, 0) * UnityEngine.Random.Range(minRadius, reproduceRadius); offset = Quaternion.AngleAxis(UnityEngine.Random.Range(0, 360), Vector3.up) * offset; var seedLocation = transform.position + offset; var cell = World.worldInstance.GetCellFromPosition(seedLocation); var tile = cell.GetWorldTile(); // If this location isn't fertile enough then bail if (tile.fertility < seedMinFertility) { return; } if (!growsInWater && tile.hydration > 0.9) { return; } List <Entity> entities = new List <Entity>(); World.worldInstance.GatherEntities(tile, maxRadius, ref entities); bool tooClose = false; foreach (var ent in entities) { // Only care about growing too close to the same type? if (ent == entity || ent.floraReproduction == null) { continue; } var distToOther = (ent.transform.position - seedLocation).magnitude; if (distToOther < (foliageType == ent.floraReproduction.foliageType? tooCloseToGrowSameType : tooCloseToGrowAnyType)) { tooClose = true; break; } } if (!tooClose) { //Debug.Log("New seedling!"); EntityManager.instance.SpawnEntity(seedLocation, entity.typeInfo); } }
public void LoadLevel() { var lines = Level.File.Split(new[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries); var boardParameters = lines.First().Split(',').Select(int.Parse).ToList(); var width = boardParameters[0]; var height = boardParameters[1]; var board = new Board(width, height); for (var y = 0; y < height; y++) { var line = lines[y + 1].Split(WidthSeparator.ToCharArray()); for (var x = 0; x < width; x++) { var cell = line[x].Split(DepthSeparator.ToCharArray()); var piecePrefabName = cell[0]; var botPrefabName = cell[1]; var tilePrefabName = cell[2]; Piece piece = null; Bot bot = null; var tileType = TileType.Hole; if (piecePrefabName != string.Empty) { var isRandom = piecePrefabName == "piece"; var pieceNumber = isRandom ? Random.Next(100) : int.Parse(piecePrefabName.Substring(5)); var pieceTransform = CreateGameObject("piece", x, y, 1); piece = new Piece(new Vector2Int(x, y), pieceNumber, pieceTransform, isRandom); } if (botPrefabName != string.Empty) { var botTransform = CreateGameObject(botPrefabName, x, y, 1); var botAnimator = botTransform.GetComponent <BotAnimator>(); bot = new Bot(new Vector2Int(x, y), botAnimator); botAnimator.Bot = bot; } if (tilePrefabName != string.Empty) { var rotation = Quaternion.identity; if (y == 0 || y == height - 1) { rotation = Quaternion.AngleAxis(90, Vector3.forward); if (x == 0 && y == 0) { rotation = Quaternion.AngleAxis(90, Vector3.back); } if (x == 0 && y == height - 1) { rotation = Quaternion.AngleAxis(180, Vector3.forward); } if (x == width - 1 && y == 0) { rotation = Quaternion.AngleAxis(0, Vector3.forward); } } var tile = CreateGameObject(tilePrefabName, x, y, 2, rotation).GetComponent <Tile>(); tileType = tile.TileType; } var field = new Field(tileType, bot, piece); board[x, y] = field; } } _board = board; ClipLevel(); GameObject.Find("ExecutionIndicatorManager").GetComponent <ExecutionIndicatorManager>() .AssignColorsToBots(_board.Bots); }
void Positioning() { var enemyMoving = isEnemyTargetMoving(); bool CannonPointing; string SideToAttack; IsCannonPointingToTarget(transform, enemy, out CannonPointing, out SideToAttack); if (CannonPointing && SideToAttack != null) { dist = Vector3.Distance(transform.position, enemy.position); CannonShotNPC instance = gameObject.GetComponent <CannonShotNPC>(); instance.ShotSide(SideToAttack); } var AdjustOrMove = Random.Range(1, 4); if (adjustingComplete && AdjustOrMove == 1) { AdjustOrMove = 2; } if (!coroutineRunning) { if (AdjustOrMove == 1) { StartCoroutine(AdjustingCannon()); } else if (AdjustOrMove == 2) { var xc = RandomPointInAnnulus(new Vector2(enemy.transform.position.x, enemy.transform.position.z), minShootingRange, maxShootingRange); StartCoroutine(Move(xc)); } else { StartCoroutine(RotateAround()); } } IEnumerator Move(Vector3 rndPos) { coroutineRunning = true; Vector3 targetDir = rndPos - transform.position; bool stillRotating = false; do { var oldEulerAngles = transform.rotation.eulerAngles.y; Quaternion rotDir = Quaternion.LookRotation(targetDir); transform.rotation = Quaternion.RotateTowards(transform.rotation, rotDir, Time.deltaTime * 20f); if (oldEulerAngles == transform.rotation.eulerAngles.y) { stillRotating = true; } Debug.DrawLine(transform.position, rndPos); yield return(null); } while (!IsLookingAtObject(transform.forward, targetDir) && !stillRotating); do { shipMovement.forward = true; Debug.DrawLine(transform.position, rndPos); yield return(null); } while (isShipInsideSphere(transform.position, rndPos) && IsLookingAtObject(transform.forward, targetDir)); shipMovement.forward = false; adjustingComplete = false; coroutineRunning = false; } IEnumerator RotateAround() { coroutineRunning = true; Side side = LeftOrRight(enemy.gameObject); var countDown = 10f; if (side == Side.RIGHT) { for (int i = 0; i < 100; i++) { do { Debug.Log(i++); countDown -= Time.smoothDeltaTime; transform.RotateAround(enemy.position, Vector3.up, 5 * Time.deltaTime); Vector3 targetDir = enemy.position - transform.position; Quaternion rotDir = Quaternion.LookRotation(targetDir); Quaternion LookAtRotationOnly_Y = Quaternion.Euler(transform.rotation.eulerAngles.x, rotDir.eulerAngles.y - 90, transform.rotation.eulerAngles.z); transform.rotation = Quaternion.Slerp(transform.rotation, LookAtRotationOnly_Y, Time.deltaTime * 1f); yield return(null); } while (countDown >= 0); } } else { for (int i = 0; i < 100; i++) { do { //Debug.Log(i++); countDown -= Time.smoothDeltaTime; transform.RotateAround(enemy.position, Vector3.up, -5 * Time.deltaTime); Vector3 targetDir = enemy.position - transform.position; Quaternion rotDir = Quaternion.LookRotation(targetDir); Quaternion LookAtRotationOnly_Y = Quaternion.Euler(transform.rotation.eulerAngles.x, rotDir.eulerAngles.y + 90, transform.rotation.eulerAngles.z); transform.rotation = Quaternion.Slerp(transform.rotation, LookAtRotationOnly_Y, Time.deltaTime * 1f); yield return(null); } while (countDown >= 0); } } coroutineRunning = false; } IEnumerator AdjustingCannon() { coroutineRunning = true; var sideFacing = 0; Side side;// = LeftOrRight(enemy.gameObject); if (Random.Range(1, 3) == 1) { sideFacing = 90; side = Side.LEFT; cannon1 = L_cannon1; } else { sideFacing = -90; side = Side.RIGHT; cannon1 = R_cannon1; } if (side == Side.RIGHT) { do { Vector3 targetDir = enemy.position - transform.position; Quaternion rotDir = Quaternion.LookRotation(targetDir); Quaternion LookAtRotationOnly_Y = Quaternion.Euler(transform.rotation.eulerAngles.x, rotDir.eulerAngles.y + sideFacing, transform.rotation.eulerAngles.z); transform.rotation = Quaternion.Slerp(transform.rotation, LookAtRotationOnly_Y, Time.deltaTime * 1f); yield return(null); } while (!IsLookingAtObject(cannon1.transform, enemy, transform.right)); } else { do { Vector3 targetDir = enemy.position - transform.position; Quaternion rotDir = Quaternion.LookRotation(targetDir); Quaternion LookAtRotationOnly_Y = Quaternion.Euler(transform.rotation.eulerAngles.x, rotDir.eulerAngles.y + sideFacing, transform.rotation.eulerAngles.z); transform.rotation = Quaternion.Slerp(transform.rotation, LookAtRotationOnly_Y, Time.deltaTime * 1f); yield return(null); } while (!IsLookingAtObject(cannon1.transform, enemy, -transform.right)); } adjustingComplete = true; coroutineRunning = false; //StartCoroutine(Attacking()); } if (Vector3.Distance(transform.position, enemy.transform.position) > maxShootingRange) { StopAllCoroutines(); coroutineRunning = false; SwitchState(State.CHASE); } Vector3 xyz = (enemy.transform.position - transform.position).normalized; Vector3 newVec1 = (Quaternion.AngleAxis(45, transform.up) * xyz) * maxShootingRange; Vector3 newVec2 = (Quaternion.AngleAxis(-45, transform.up) * xyz) * maxShootingRange; /* * Debug.DrawRay(transform.position, xyz * 50, Color.green, 1); * Debug.DrawRay(enemy.position, newVec1, Color.black, 1); * Debug.DrawRay(enemy.position, newVec2, Color.black, 1); */ }
protected void RotateRubixCube(Vector3 axis, float angleInDeg) { transform.rotation = Quaternion.AngleAxis(angleInDeg, axis) * transform.rotation; RefreachPrecisionPlane(); }