private void PlaceMode() { if (BuildingSelector.SelectedBuilding == null) { return; } if (tilesHoveringOver != null) { RevertTileColorsToBase(); } bool isHitting = false; tilesHoveringOver = GetTilesAt(RaycastHelper.GetMousePositionInScene(out isHitting), new IntVector2(BuildingSelector.SelectedBuilding.xSize, BuildingSelector.SelectedBuilding.zSize)); if (tilesHoveringOver == null) { return; } AdjustTileColors(); if (Input.GetMouseButtonDown(0) && CanBePlaced(tilesHoveringOver) && BuildingSelector.SelectedBuilding.CanBeBought()) { PlaceBuilding(BuildingSelector.SelectedBuilding, tilesHoveringOver, false); } }
public void Execute(IRocketPlayer caller, string[] command) { UnturnedPlayer player = (UnturnedPlayer)caller; Transform transform = RaycastHelper.GetBarricadeTransform(player.Player, out _, out BarricadeDrop drop); if (transform == null || drop.interactable as InteractableDoor == null) { MessageHelper.Send(caller, "DoorNotLooking"); return; } Door door = pluginInstance.DoorService.GetDoor(transform); if (door == null || door.IsSold) { MessageHelper.Send(caller, "DoorNotForSale"); return; } decimal balance = Uconomy.Instance.Database.GetBalance(caller.Id); if (balance < door.Price) { MessageHelper.Send(caller, "BuyDoorCantAfford", door.PriceString); return; } Uconomy.Instance.Database.IncreaseBalance(caller.Id, -door.Price); Uconomy.Instance.Database.IncreaseBalance(door.OwnerId, door.Price); pluginInstance.DoorService.BuyDoor(door, player.Player); MessageHelper.Send(caller, "BuyDoorSuccess", door.PriceString); }
private void DestroyMode() { BuildingSelector.SetToNull(); bool isHitting = true; RaycastHelper.GetMousePositionInScene(out isHitting); if (tilesHoveringOver != null) { RevertTileColorsToBase(); } if (isHitting == false) { return; } try { tilesHoveringOver = GetTilesAt(RaycastHelper.GetMousePositionInScene(out isHitting), new IntVector2(1, 1)); AdjustTileColors(); if (Input.GetMouseButtonDown(0) && tilesHoveringOver != null && tilesHoveringOver[0, 0].occupant != null) { DestroyBuilding(tilesHoveringOver[0, 0]); } } catch { } }
protected void DropThroughOneWayPlatform() //Drop through a one-way platform { if (RaycastHelper.DropThroughFloorRaycast((Direction.Vertical)(GravityScaleMultiplier() * -1.0f), slots.actor.GetComponent <BoxCollider2D>(), GravityScaleMultiplier())) { StartCoroutine("DisableOneWayPlatformsCoroutine"); } }
protected BufferZoneInfo GetBufferZoneInfo(float gravityScale, Direction.Vertical verticalDirection) { BufferZoneInfo bufferZoneInfo = new BufferZoneInfo(); bool willSnapToLedgeHeight = wallClimb.enableClimbing || ledgeGrab.enableLedgeGrab; if(willSnapToLedgeHeight) { RaycastHelper.LedgeInfo ledgeInfo = RaycastHelper.DetectLedgeOnWall(controller.direction.horizontal, (Direction.Vertical)((int)verticalDirection * gravityScale), controller.slots.actor.GetComponent<BoxCollider2D>(), controller.slots.physicsObject.properties.velocity.y * PhysicsManager.Instance.fixedDeltaTime * -(int)verticalDirection); if(!ledgeInfo.didHit) { ledgeInfo = RaycastHelper.DetectLedgeOnWall(controller.direction.horizontal, (Direction.Vertical)((int)verticalDirection * gravityScale), controller.slots.actor.GetComponent<BoxCollider2D>(), controller.slots.physicsObject.properties.velocity.y * PhysicsManager.Instance.fixedDeltaTime * -(int)verticalDirection, 0.0f); } if(ledgeInfo.didHit) { bufferZoneInfo.isLedgeDetected = true; bufferZoneInfo.bufferCutoff = ledgeInfo.hitY - (controller.slots.actor.GetComponent<BoxCollider2D>().size.y * 0.5f * gravityScale * -(int)verticalDirection); float adjustedPositionY = transform.position.y + controller.slots.physicsObject.properties.velocity.y * PhysicsManager.Instance.fixedDeltaTime * -(int)verticalDirection; if(verticalDirection == Direction.Vertical.Down && ((gravityScale < 0.0f && adjustedPositionY < bufferZoneInfo.bufferCutoff) || (gravityScale > 0.0f && adjustedPositionY > bufferZoneInfo.bufferCutoff))) //At top of wall { bufferZoneInfo.isInBufferZone = true; } else if(verticalDirection == Direction.Vertical.Up && ((gravityScale < 0.0f && adjustedPositionY > bufferZoneInfo.bufferCutoff) || (gravityScale > 0.0f && adjustedPositionY < bufferZoneInfo.bufferCutoff))) { bufferZoneInfo.isInBufferZone = true; } } } return bufferZoneInfo; }
public void Execute(IRocketPlayer caller, string[] command) { UnturnedPlayer player = (UnturnedPlayer)caller; Transform transform; transform = RaycastHelper.GetBarricadeTransform(player.Player, out _, out _); if (transform == null) { transform = RaycastHelper.GetStructureTransform(player.Player, out _); } if (transform == null) { MessageHelper.Send(caller, "DoorNotLooking"); return; } Door door = pluginInstance.DoorService.GetDoorOrItem(transform); if (door == null) { MessageHelper.Send(caller, "DoorNotForSale"); return; } MessageHelper.Send(caller, "CheckDoorSuccess", door.Id, door.PriceString, door.OwnerName); }
protected override async Task OnExecuteAsync() { UnturnedUser user = (UnturnedUser)Context.Actor; InteractableVehicle?vehicle = RaycastHelper.Raycast(user.Player.Player, 6f); if (vehicle != null) { string ownerId = await m_KeysManager.CheckVehicleOwner(vehicle.instanceID); if (ownerId != "") { await m_KeysManager.TryRemoveKeyFromBunch(ownerId, vehicle.instanceID); await user.PrintMessageAsync(m_StringLocalizer["translations:vehicle_removedkey", new { vehicleID = vehicle.instanceID }]); var player = PlayerTool.getPlayer(new Steamworks.CSteamID(ulong.Parse(ownerId))); if (player != null) { ChatManager.say(player.channel.owner.playerID.steamID, m_StringLocalizer["translations:vehicle_lockpicked", new { vehicle = vehicle.asset.name, vehicleID = vehicle.instanceID }], UnityEngine.Color.red, EChatMode.SAY, true); } } } else { await user.PrintMessageAsync(m_StringLocalizer["translations:vehicle_notfound"], System.Drawing.Color.Red, false, ""); } }
private void LoadDoors(int i) { database.Reload(); foreach (Door door in database.Doors) { Vector3 pos = door.Position.ToVector3(); door.Transform = RaycastHelper.GetBarricadeTransform(pos); if (door.Transform == null) { Logger.LogWarning($"Door #{door.Id} transform not found"); } foreach (DoorItem item in door.Items) { pos = item.Position.ToVector3(); if (item.IsBarricade) { item.Transform = RaycastHelper.GetBarricadeTransform(pos); } else { item.Transform = RaycastHelper.GetStructureTransform(pos); } if (item.Transform == null) { Logger.LogWarning($"Door #{door.Id} item transform not found"); } } } }
public override void OnUpdate(float frameTime, PauseMode pauseMode) { base.OnUpdate(frameTime, pauseMode); // Raycast from the position of this object down using the specified distance. RayOut = RaycastHelper.Raycast(Position, Vec3.Down, Distance); // Set color based on hit type. // Unknown = Red // Terrain = Green // Entity = Blue // Other (Designer/Brush) = White ColorB color = null; switch (RayOut.Type) { case RaycastOutput.HitType.Unknown: color = new ColorB(255, 0, 0); break; case RaycastOutput.HitType.Terrain: color = new ColorB(0, 255, 0); break; case RaycastOutput.HitType.Entity: color = new ColorB(0, 0, 255); break; case RaycastOutput.HitType.Static: color = new ColorB(255, 255, 255); break; default: break; } // Draw debug helpers. var renderer = Env.AuxRenderer; renderer.DrawSphere(Position, 0.25f, color, false); renderer.DrawLine(Position, color, RayOut.Point, color, 4f); // Draw additional debug helpers if the ray hit something. if (RayOut.Intersected) { renderer.DrawCylinder(RayOut.Point, Vec3.Up, 0.5f, 0.1f, color); } // Draw information about what was hit. Displays 'Hit: Type' if not hitting an entity, otherwise 'Hit: Type (EntityName)'. var info = string.Format("Hit: {0} ({1})", RayOut.Type.ToString(), RayOut.HitBaseEntity != null ? RayOut.HitBaseEntity.Name : ""); Env.AuxRenderer.Draw2dLabel(Screen.Width / 2f, Screen.Height - 55, 2, new ColorF(), true, info); var distance = string.Format("Distance: {0}", RayOut.Distance); Env.AuxRenderer.Draw2dLabel(Screen.Width / 2f, Screen.Height - 35, 2, new ColorF(), true, distance); }
void Start() { cam = Camera.main; rayHelper = new RaycastHelper(); state = States.Free; UIHolder.gameObject.SetActive(false); buildSel = BuildingSel.Nothing; #if !UNITY_EDITOR fingerID = 0; #endif }
public void Execute(int index) { var arrow = arrows[index]; // Check if the arrow is fired if (arrow.active) { arrow.position += arrow.velocity * dt; arrow.velocity.y += SimulationState.Gravity * dt; // Check if we hit something int i = 0; int hash = MinionSystem.Hash(arrow.position); NativeMultiHashMapIterator <int> iterator; bool found = buckets.TryGetFirstValue(hash, out i, out iterator); int iterations = 0; while (found) { if (iterations++ > 3) { break; } // This freezes :/ var relative = arrow.position - allMinionTransforms[i].Position; var distance = math.length(relative); if (distance < 1f) { if ((arrow.IsFriendly == 1) != minionConstData[i].IsFriendly) { // Deal damage and deactivate the arrow AttackCommands.Enqueue(new AttackCommand(arrowEntities[index], minionEntities[i], 34)); // Send it to the end of the earth arrow.active = false; arrow.position = Vector3.one * -1000000; queueForKillingEntities.Enqueue(arrowEntities[index]); break; } } found = buckets.TryGetNextValue(out i, ref iterator); } if (arrow.active) { raycastCommands[index] = RaycastHelper.CreateRaycastCommand(arrow.position); } arrows[index] = arrow; } }
public void UpdateWayPoint(int minRange = -500, int maxRange = 500) { points.Clear(); for (int x = minRange; x < maxRange; x++) { for (int z = minRange; z < maxRange; z++) { WayPoint p = new WayPoint(); p.hitPoint = new Vector3(x, -1001, z); bool isHit = false; for (int j = 0, c0 = meshFilters.Count; j < c0; j++) { var mr = meshRenders[j]; var mf = meshFilters[j]; var max = mr.bounds.max; var min = mr.bounds.min; if (min.x < x && x < max.x && min.z < z && z < max.z) { RaycastHit hitInfor; if (RaycastHelper.Raycast(mf, new Ray(new Vector3(x, 500, z), Vector3.down), out hitInfor, 1000f)) { if (isHit) { if (hitInfor.point.y > p.hitPoint.y) { p.hitPoint = hitInfor.point; } } else { p.hitPoint = hitInfor.point; } isHit = true; } } } if (isHit) { p.pos = new LVector3Int(SafeInt(p.hitPoint.x), SafeHeight(p.hitPoint.y), SafeInt(p.hitPoint.z)); if (type == TYPE.WAY) { p.airPoints = new Vector3[4]; p.screenPoints = new Vector3[4]; p.airPoints[0] = p.pos + new Vector3(-0.5f, 0.5f, -0.5f); p.airPoints[1] = p.pos + new Vector3(0.5f, 0.5f, -0.5f); p.airPoints[2] = p.pos + new Vector3(-0.5f, 0.5f, 0.5f); p.airPoints[3] = p.pos + new Vector3(0.5f, 0.5f, 0.5f); } points.Add(p); } } } }
public bool CanExitCrouch() { bool canExit = true; Direction.Vertical direction = (Direction.Vertical)controller.GravityScaleMultiplier(); if (RaycastHelper.IsUnderOverhang(direction, nonCrouchingColliderSize, boxCollider.transform.position)) { canExit = false; } return(canExit); }
public void Execute(IRocketPlayer caller, string[] command) { if (command.Length < 1) { MessageHelper.Send(caller, "SellDoorFormat"); return; } if (!decimal.TryParse(command[0], out decimal price)) { MessageHelper.Send(caller, "SellDoorWrongPrice", command[0]); return; } price = Math.Abs(price); UnturnedPlayer player = (UnturnedPlayer)caller; Transform transform = RaycastHelper.GetBarricadeTransform(player.Player, out BarricadeData barricadeData, out BarricadeDrop drop); if (transform == null || drop.interactable as InteractableDoor == null) { MessageHelper.Send(caller, "DoorNotLooking"); return; } if (barricadeData.owner != player.CSteamID.m_SteamID) { MessageHelper.Send(caller, "DoorNotOwner"); return; } Door door = pluginInstance.DoorService.GetDoor(transform); // update door price if (door != null) { pluginInstance.DoorService.UpdateDoorPrice(door, price, player.Player); MessageHelper.Send(caller, "SellDoorSuccess", door.Id, door.PriceString); return; } if (!player.IsAdmin && !player.HasPermission("selldoor.admin")) { MessageHelper.Send(caller, "SellDoorNoPermission"); return; } door = pluginInstance.DoorService.SellDoor(transform, price, player.Player); MessageHelper.Send(caller, "SellDoorSuccess", door.Id, door.PriceString); }
private void UnturnedPlayerEvents_OnPlayerUpdateGesture(UnturnedPlayer player, UnturnedPlayerEvents.PlayerGesture gesture) { Player victimPlayer = RaycastHelper.GetPlayerFromHits(player.Player, 2); UnturnedPlayer victim = UnturnedPlayer.FromPlayer(victimPlayer); if (victim != null) { if (gesture == UnturnedPlayerEvents.PlayerGesture.Point) { StartCoroutine(player.Player.GetComponent <PlayerComponent>().showDNI(victim, player)); } } }
protected override void Execute() { List <Transform> transforms = RaycastHelper.GetTransformOnPosition2D(Input.mousePosition); foreach (Transform transform in transforms) { bool isLevelObject = GenerateableLevelObjectLibrary.IsLevelObject(transform.name); if (isLevelObject) { Abort(); return; } } }
private void DoProjectile() { Transform projectileSpawnPoint = weaponGraphics.bulletTracerPosition; Transform playerFacingDirection = weaponManager.localPlayerCamera; //Figure out where the projectile should aim for RaycastHit[] hits = RaycastHelper.RaycastAllSorted(playerFacingDirection.position, playerFacingDirection.forward, float.MaxValue, weaponManager.raycastLayerMask); //We need to filter through each hit RaycastHit?raycastHit = null; foreach (RaycastHit hit in hits) { //Don't count if we hit the shooting player if (hit.collider.name == weaponManager.transform.name) { continue; } raycastHit = hit; } //Spawn the object GameObject newProjectile = projectileObjectsPool.GetPooledObject(); if (raycastHit.HasValue) { RaycastHit hit = raycastHit.Value; if (hit.distance > projectileAutoAimMinRange) { newProjectile.transform.LookAt(hit.point); Logger.Debug("Pointing player's projectile at cross-hair."); } } ProjectileBase projectile = newProjectile.GetComponent <ProjectileBase>(); if (projectile == null) { Logger.Error("Weapon projectile doesn't have a projectile base on it!"); return; } projectile.SetupOwner(weaponManager.playerManager); projectile.ServerEnable(projectileSpawnPoint.position, projectileSpawnPoint.rotation.eulerAngles); DoWeaponEffects(new ProjectileEffectsMessage()); }
public void Execute(IRocketPlayer caller, string[] command) { UnturnedPlayer player = (UnturnedPlayer)caller; int doorId = 0; bool flag = true; if (command.Length > 0) { flag = false; if (!int.TryParse(command[0], out doorId)) { MessageHelper.Send(caller, "WrongDoorId", command[0]); return; } } Door door; if (flag) { Transform transform = RaycastHelper.GetBarricadeTransform(player.Player, out _, out BarricadeDrop drop); if (transform == null || drop.interactable as InteractableDoor == null) { MessageHelper.Send(caller, "DoorNotLooking"); return; } door = pluginInstance.DoorService.GetDoor(transform); } else { door = pluginInstance.DoorService.GetDoor(doorId); } if (door == null) { MessageHelper.Send(caller, "DoorNotForSale"); return; } pluginInstance.DoorService.RemoveDoor(door); MessageHelper.Send(caller, "DeleteDoorSucccess", door.Id, door.Items.Count); }
public void UpdateWayPoint(int minRange = -500, int maxRange = 500) { points.Clear(); for (int x = minRange; x < maxRange; x++) { for (int z = minRange; z < maxRange; z++) { WayPoint p = new WayPoint(); p.hitPoint = new Vector3(x, -1001, z); bool isHit = false; for (int j = 0; j < meshFilters.Length; j++) { var mr = meshRenders[j]; var mf = meshFilters[j]; var max = mr.bounds.max; var min = mr.bounds.min; if (min.x < x && x < max.x && min.z < z && z < max.z) { RaycastHit hitInfor; if (RaycastHelper.Raycast(mf, new Ray(new Vector3(x, 500, z), Vector3.down), out hitInfor, 1000f)) { if (isHit) { if (hitInfor.point.y > p.hitPoint.y) { p.hitPoint = hitInfor.point; } } else { p.hitPoint = hitInfor.point; } isHit = true; } } } if (isHit) { p.pos = new Vector3(SaveInt(p.hitPoint.x), SaveInt(p.hitPoint.y), SaveInt(p.hitPoint.z)); points.Add(p); } } } }
public void Shake(Action onShake = null) { // Get a random position and amplitude. _position = GetRandomPosition(Position, RandomOffset); var amplitude = GetAmplitude(MinAmplitude, MaxAmplitude); // Get all affectors within our radius. var affectors = EntityFramework.GetEntities <Ball>() .Where(x => x.Position.GetDistance(_position) < Radius) .ToList(); affectors.ForEach(entity => { bool apply = false; if (!ApplyInAir) { // Raycast from each affector to test if it's grounded. var rayOut = RaycastHelper.Raycast(entity.Position, Vec3.Down, entity.Scale.y); // If the ray hit something, it must close enough to the ground to be considered grounded. apply = rayOut.Intersected && !rayOut.HasHitEntity(entity); } else { apply = true; } // Add an impulse to each object using our position and amplitude. if (apply) { entity.Physics.Action <pe_action_impulse>((p) => { p.point = _position; p.impulse = Vec3.Up * amplitude; }); } }); if (onShake != null) { onShake(); } }
void FixedUpdate() { if (Timer != null) { Player victimPlayer = RaycastHelper.GetPlayerFromHits(Pickpocket.Player, pluginInstance.Configuration.Instance.MaxDistance); if (victimPlayer != Victim.Player) { UnturnedChat.Say(Pickpocket.CSteamID, pluginInstance.Translate("FAIL", Victim.CharacterName), pluginInstance.MessageColor); if (pluginInstance.Configuration.Instance.NotifyVictimOnFail) { UnturnedChat.Say(Victim.CSteamID, pluginInstance.Translate("NOTIFY_FAIL", Pickpocket.CharacterName), pluginInstance.MessageColor); } Destroy(this); Timer.Dispose(); } } }
public void Execute(IRocketPlayer caller, string[] command) { UnturnedPlayer player = (UnturnedPlayer)caller; Transform transform = RaycastHelper.GetBarricadeTransform(player.Player, out _, out BarricadeDrop drop); if (transform == null || drop.interactable as InteractableDoor == null) { MessageHelper.Send(caller, "DoorNotLooking"); return; } Door door = pluginInstance.DoorService.GetDoor(transform); if (door == null || door.IsSold) { MessageHelper.Send(caller, "DoorNotForSale"); return; } MessageHelper.Send(caller, "CostDoorPrice", door.PriceString); }
private void OnTriggerSend(SteamPlayer player, string name, ESteamCall mode, ESteamPacket type, params object[] arguments) { if (name == "tellGesture") { var up = UnturnedPlayer.FromSteamPlayer(player); var id = int.Parse(arguments[0].ToString()); if (id == 8) { if (!Configuration.Instance.UsePermissions || up.HasPermission("pickpocket")) { Player victimPlayer = RaycastHelper.GetPlayerFromHits(up.Player, Configuration.Instance.MaxDistance); if (victimPlayer != null) { if (Cooldowns.TryGetValue(up.Id.ToString(), out DateTime expireDate) && expireDate > DateTime.Now) { UnturnedChat.Say(up.CSteamID, Translate("COOLDOWN", System.Math.Truncate((expireDate - DateTime.Now).TotalSeconds)), MessageColor); } else { if (expireDate != null) { Cooldowns.Remove(up.Id); } UnturnedPlayer victim = UnturnedPlayer.FromPlayer(victimPlayer); if (victim.HasPermission("bypass.pickpocket")) { UnturnedChat.Say(up, Translate("BYPASS"), MessageColor); return; } PickpocketComponent comp = up.Player.gameObject.AddComponent <PickpocketComponent>(); comp.Initialize(up, victim, this); Cooldowns.Add(up.Id, DateTime.Now.AddSeconds(Configuration.Instance.PickpocketCooldown)); } } } } } }
// Update is called once per frame void Update() { if (!UseVisibilityController) { _Renderer.enabled = true; m_LaserRenderer.enabled = true; return; } if (ShowLoadingObject && m_LoadingObj) { m_LoadingObj.transform.position = GvrPointerInputModule.Pointer.CurrentRaycastResult.worldPosition; m_LoadingObj.SetActive(true); } else if (m_LoadingObj) { m_LoadingObj.SetActive(false); } bool overUi = RaycastHelper.IsPointerOverUIObject(); _Renderer.enabled = overUi; if (m_LaserRenderer) { m_LaserRenderer.enabled = overUi; } if (StayHidden) { _Renderer.enabled = false; } else if (HideOneFrame) { _Renderer.enabled = false; HideOneFrame = false; } }
public void Execute(IRocketPlayer caller, string[] command) { UnturnedPlayer player = (UnturnedPlayer)caller; string name = string.Empty; Transform transform = RaycastHelper.GetBarricadeTransform(player.Player, out BarricadeData barricadeData, out BarricadeDrop drop); if (transform == null) { transform = RaycastHelper.GetStructureTransform(player.Player, out StructureData structureData); if (transform != null) { name = structureData.structure.asset.itemName; } } else { name = barricadeData.barricade.asset.itemName; } if (transform == null) { MessageHelper.Send(caller, "DoorItemNotLooking"); return; } Door door = pluginInstance.DoorService.GetDoorFromItem(transform); if (door == null) { MessageHelper.Send(caller, "NotDoorItem", name); return; } pluginInstance.DoorService.RemoveDoorItem(door, transform); MessageHelper.Send(caller, "UnlinkDoorSuccess", name, door.Id); }
private void WeaponRayCast() { Transform playerFacingDirection = weaponManager.localPlayerCamera; Vector3 direction = playerFacingDirection.forward; RaycastHit[] hits = RaycastHelper.RaycastAllSorted(playerFacingDirection.position, direction, weaponRange, weaponManager.raycastLayerMask); Vector3?hitPoint = null; Vector3?hitNormal = null; //We need to filter through each hit foreach (RaycastHit hit in hits) { //Don't count if we hit the shooting player if (hit.collider.name == weaponManager.transform.name) { continue; } hitPoint = hit.point; hitNormal = hit.normal; //So if we hit a player then do damage PlayerManager hitPlayer = hit.collider.GetComponent <PlayerManager>(); if (hitPlayer == null) { break; } hitPlayer.TakeDamage(weaponDamage, weaponManager.transform.name); break; } DoWeaponEffects(new MeleeEffectsMessage(hitPoint, hitNormal)); }
public override void SolverUpdate() { // Pass-through by default this.GoalPosition = WorkingPos; this.GoalRotation = WorkingRot; // Determine raycast params Ray ray = new Ray(GetRaycastOrigin(), GetRaycastDirection()); // Skip if there's no valid direction if (ray.direction == Vector3.zero) { return; } float ScaleOverride = GetScaleOverride(); float len; bool bHit; RaycastResultHelper result; Vector3 hitDelta; switch (raycastMode) { case RaycastModeEnum.Simple: default: // Do the cast! bHit = DefaultRaycast(ray.origin, ray.direction, MaxDistance, MagneticSurface, out result); OnSurface = bHit; if (UseTexCoordNormals) { result.OverrideNormalFromTextureCoord(); } // Enforce CloseDistance hitDelta = result.Point - ray.origin; len = hitDelta.magnitude; if (len < CloseDistance) { result.OverridePoint(ray.origin + ray.direction * CloseDistance); } // Apply results if (bHit) { GoalPosition = result.Point + SurfaceNormalOffset * result.Normal + SurfaceRayOffset * ray.direction; GoalRotation = CalculateMagnetismOrientation(ray.direction, result.Normal); } break; case RaycastModeEnum.Box: Vector3 scale = transform.lossyScale; if (ScaleOverride > 0) { scale = scale.normalized * ScaleOverride; } Quaternion orientation = orientationMode == OrientModeEnum.None ? Quaternion.LookRotation(ray.direction, Vector3.up) : CalculateMagnetismOrientation(ray.direction, Vector3.up); Matrix4x4 targetMatrix = Matrix4x4.TRS(Vector3.zero, orientation, scale); if (m_BoxCollider == null) { m_BoxCollider = this.GetComponent <BoxCollider>(); } Vector3 extents = m_BoxCollider.size; Vector3[] positions; Vector3[] normals; bool[] hits; if (RaycastHelper.CastBoxExtents(extents, transform.position, targetMatrix, ray, MaxDistance, MagneticSurface, DefaultRaycast, BoxRaysPerEdge, OrthoBoxCast, out positions, out normals, out hits)) { Plane plane; float distance; // place an unconstrained plane down the ray. Never use vertical constrain. FindPlacementPlane(ray.origin, ray.direction, positions, normals, hits, m_BoxCollider.size.x, MaximumNormalVariance, false, orientationMode == OrientModeEnum.None, out plane, out distance); // If placing on a horzizontal surface, need to adjust the calculated distance by half the app height float verticalCorrectionOffset = 0; if (IsNormalVertical(plane.normal) && !Mathf.Approximately(ray.direction.y, 0)) { float boxSurfaceOffsetVert = targetMatrix.MultiplyVector(new Vector3(0, extents.y / 2f, 0)).magnitude; Vector3 correctionVec = boxSurfaceOffsetVert * (ray.direction / ray.direction.y); verticalCorrectionOffset = -correctionVec.magnitude; } float boxSurfaceOffset = targetMatrix.MultiplyVector(new Vector3(0, 0, extents.z / 2f)).magnitude; // Apply boxSurfaceOffset to rayDir and not surfaceNormalDir to reduce sliding GoalPosition = ray.origin + ray.direction * Mathf.Max(CloseDistance, distance + SurfaceRayOffset + boxSurfaceOffset + verticalCorrectionOffset) + plane.normal * (0 * boxSurfaceOffset + SurfaceNormalOffset); GoalRotation = CalculateMagnetismOrientation(ray.direction, plane.normal); OnSurface = true; } else { OnSurface = false; } break; case RaycastModeEnum.Sphere: // Do the cast! float size = ScaleOverride > 0 ? ScaleOverride : transform.lossyScale.x * SphereSize; bHit = DefaultSpherecast(ray.origin, ray.direction, size, MaxDistance, MagneticSurface, out result); OnSurface = bHit; // Enforce CloseDistance hitDelta = result.Point - ray.origin; len = hitDelta.magnitude; if (len < CloseDistance) { result.OverridePoint(ray.origin + ray.direction * CloseDistance); } // Apply results if (bHit) { GoalPosition = result.Point + SurfaceNormalOffset * result.Normal + SurfaceRayOffset * ray.direction; GoalRotation = CalculateMagnetismOrientation(ray.direction, result.Normal); } break; } // Do frame to frame updates of transform, smoothly toward the goal, if desired UpdateWorkingPosToGoal(); UpdateWorkingRotToGoal(); }
protected void CheckLadders(float _inputDirection) { if (isClimbing && isEnabled) { float topBuffer = 0.1f; bool isOnTopOfLadder = (controller.GravityScaleMultiplier() > 0.0f) ? !(boxCollider.bounds.min.y < activeLadderTopCrestPosition - topBuffer) : !(boxCollider.bounds.max.y > activeLadderBottomCrestPosition + topBuffer); if (!isOnTopOfLadder) //You're not on top of the ladder { isTouching = true; } } if (!isEnabled && isClimbing) { Drop(); } if (!isEnabled || controller.framesSinceDrop < 10) { return; } if (isTouching) { if (_inputDirection == 1.0f && !IsLockedForAttack(Attack.ActionType.Climbing) && !controller.isKnockbackActive && !controller.isStunned && !isClimbing && IsHorizontallyCenteredOnLadder()) //Mount a ladder { Begin(); controller.slots.physicsObject.SetVelocityX(0.0f); isClimbing = true; willAllowDirectionChange = false; } else if (controller.slots.input && controller.slots.input.isJumpButtonDownThisFrame && isClimbing) { Drop(); } else if (_inputDirection == -1.0f && controller.slots.physicsObject.IsOnSurface() && isClimbing) //Dismounting by climbing to the floor { End(); } } else { if (!controller.isKnockbackActive) //On top of a ladder; going down { if (_inputDirection == -1.0f && !IsLockedForAttack(Attack.ActionType.Climbing)) { if (RaycastHelper.IsOnSurface("Ladder", (Direction.Vertical)(-1.0f * controller.GravityScaleMultiplier()), boxCollider)) { Collider2D col = RaycastHelper.GetColliderForSurface("Ladder", (Direction.Vertical)(-1.0f * controller.GravityScaleMultiplier()), boxCollider); SetLadderValues(col); if (!IsHorizontallyCenteredOnLadder()) { return; } controller.slots.actor.SetPosition(new Vector2(activeLadderXPosition, transform.position.y)); controller.slots.physicsObject.SetVelocityX(0); isClimbing = true; willAllowDirectionChange = false; Begin(); controller.slots.physicsObject.SetVelocityX(0.0f); controller.slots.actor.SetPosition(new Vector2(transform.position.x, transform.position.y - (0.25f * controller.GravityScaleMultiplier()))); } } } } }
private static bool DefaultSpherecast(Vector3 origin, Vector3 direction, float radius, float distance, LayerMask surface, out RaycastResultHelper result) { return(RaycastHelper.SphereFirst(origin, direction, radius, distance, surface, out result)); }
void Start() { rh = new RaycastHelper(EscenaOle.arCamera); dragMe = GetComponent <DragMe>(); }