public BoardPosition GetPositionForGO(GameObject go) { BoardPosition position = default(BoardPosition); foreach (KeyValuePair<BoardPosition, GameObject> tile in board) { if (go.Equals(tile.Value)) { position = tile.Key; break; } Renderer r = tile.Value.GetComponent<Renderer>(); if (r != null) { Bounds b = r.bounds; if (go.transform.position.x >= b.min.x && go.transform.position.x <= b.max.x && go.transform.position.y >= b.min.y && go.transform.position.y <= b.max.y) { position = tile.Key; break; } } } return position; }
void OnDied(GameObject enemy) { if (enemy.Equals (gameObject)) { innerRotate.StopSmooth(); outterRotate.StopSmooth(); if(dropMinionsOnDeath) { foreach(Transform t in transform.FindChild("Minions")) { t.parent = transform.parent; foreach(EnemyMovement enemyMovement in t.GetComponents<EnemyMovement>()) { if(enemyMovement.GetType() == typeof(RandomMovement)) enemyMovement.enabled = true; else enemyMovement.enabled = false; } //collider was disabled when parent changed t.GetComponentInChildren<Collider2D>().enabled = true; if(OnMinionReleased != null) OnMinionReleased(t.gameObject); } } else { RemoveMinions(); } } }
void OnParticleCollision( GameObject other) { if ( other.Equals( GameObject.FindWithTag( "Player" ) ) ) { mm.increaseMovementSpeedTemporarily(); } }
public void leavePoop(GameObject collectable) { if (collectable.Equals (currentCollectable)) { onPoop = false; currentCollectable = null; } }
void OnDestroyChild(GameObject target) { if (target.Equals(maxCautionEnemy)) { maxCautionEnemy = null; if(ui)ui.BroadcastMessage("OnUpdateCaution", 0, SendMessageOptions.DontRequireReceiver); } }
public void updateSelector(GameObject newText) { // Gets called from the text itself to tell this script a mouse is pointing at it. for (int i = 0; i < selectedArray.Length; i++) { if ( newText.Equals (selectedArray[i])) { selectNum = i; changeSelector (); } } }
public override void otherCollisionEnter(GameObject enemy,Vector3 point) { if(enemy.GetComponent<HydraPlatform>()!=null){ enemy.GetComponent<HydraPlatform>().hasBeenTouched(); if(iaParent.platformDestroyed !=null && !enemy.Equals(iaParent.platformDestroyed)){ iaParent.platformDestroyed.GetComponent<HydraPlatform>().repositionPlatform(); } iaParent.platformDestroyed = enemy; } }
public override void OnPreferencesSaved() { var oldColor = textColor; textColor = new Color(Utils.Clamp(textR.Value, 0, 100) / 100f, Utils.Clamp(textG.Value, 0, 100) / 100f, Utils.Clamp(textB.Value, 0, 100) / 100f); if ((!AudioPage?.Equals(null) ?? false) && oldColor != textColor) { SetColor(); } }
public static string LightDetailsString(GameObject selLight) { if (!selLight?.Equals(null) ?? false) { var _light = selLight; return($"{_light.name}\n{_light.GetOrAddComponent<Light>().type}\nR:{_light.GetOrAddComponent<Light>().color.r} G:{_light.GetOrAddComponent<Light>().color.g}" + $" B:{_light.GetOrAddComponent<Light>().color.b}\nInten:{Utils.NumFormat(_light.GetOrAddComponent<Light>().intensity)}"); } return("Null"); }
public bool isItemTouchingInventory(GameObject itemToCheck) { foreach(GameObject item in itemInInventoryTrigger) { if(itemToCheck.Equals(item)) { return true; } } return false; }
public bool hasConnectingPath(GameObject node) { foreach (GameObject path in connectedPaths) { if (node.Equals(path)) { return true; } } return false; }
public GameObject GetRandomDestination(GameObject current) { bool foundDest = false; GameObject go = null; while(!foundDest){ int i = Random.Range (0, navPoints.Length); go = navPoints[i]; foundDest = (go.GetComponent<NavpointScript>().isDestination && !current.Equals (go)); } return go; }
public Transform getParentFromItem(GameObject itemToCheck) { foreach(ItemParentSave item in itemInInventory) { if(itemToCheck.Equals(item.ItemGameObject)) { return item.parent; } } return null; }
public bool isItemStoredInInventory(GameObject itemToCheck) { foreach(ItemParentSave item in itemInInventory) { if(itemToCheck.Equals(item.ItemGameObject)) { return true; } } return false; }
public void ShootTarget(GameObject target) { if(!target.Equals(targetCharacter)) { if(OnBeginAttacking != null) OnBeginAttacking(target); StopCoroutine("castShot"); targetCharacter = target; StartCoroutine("castShot"); } }
public static void ToggleObject() { if (!fluxObj?.Equals(null) ?? false) { try { UnityEngine.Object.Destroy(fluxObj); } catch (System.Exception ex) { Logger.Error(ex.ToString()); } fluxObj = null; isEnabled = false; } else { GameObject obj = GameObject.Instantiate(fluxPrefab); GameObject cam = Camera.main.gameObject; obj.transform.SetParent(cam.transform); obj.transform.localPosition = new Vector3(0f, 0f, 0f); obj.layer = 5; fluxObj = obj; OnValueChange(0f, 0f); isEnabled = true; } }
public void Bounce(GameObject bounce) { if (bounce.Equals(bouncePointer1)) { bouncePointer2.SetActive(true); bouncePointer1.SetActive(false); realDeepThroat.destination = bouncePointer2.transform.position; } else { bouncePointer1.SetActive(true); bouncePointer2.SetActive(false); realDeepThroat.destination = bouncePointer1.transform.position; } }
public void MoveToward(GameObject targetCharacter) { if(!targetCharacter.Equals(moveTarget)) { moveTarget = targetCharacter; MoveTo(targetCharacter.transform.position); } else { moveTargetPosition = targetCharacter.transform.position; //moveTargetPosition.z = 0; } }
bool CheckKeyMatching(GameObject a) { if (!GetOn()) return false; bool _match = false; foreach (GameObject item in Key) { if (a.Equals(item)) { _match = true; break; } } return _match; }
IEnumerator MoveDown(GameObject uiElement) { float smoothing = 8f; Vector2 target = new Vector2(0, 0); while(Vector2.Distance(uiElement.transform.localPosition, target) > 0.05f) { uiElement.transform.localPosition = Vector2.Lerp(uiElement.transform.localPosition, target, smoothing * Time.deltaTime); yield return null; } yield return new WaitForSeconds(.1f); if (uiElement.Equals (instructions)) { GameObject.Find ("Player").GetComponent<PlayerController>().CanInput = true; } }
// Update is called once per frame void Update() { RaycastHit hitPos; Ray click = Camera.main.ScreenPointToRay(Input.mousePosition); if(Physics.Raycast(click, out hitPos)) { if(hitPos.transform.tag == "Agent" && Input.GetMouseButtonDown(0)) { unit = hitPos.transform.gameObject; //check to see if unit already selected for(int a = 0; a <= selCount; a++) { if (unit.Equals(unitArr[a])) checker = true; } //adds unit to array, "selects" it if (!checker) { unit.SendMessage("Select", 1); Debug.Log(selCount); unitArr[selCount] = unit; selCount++; checker = false; } } //use right-click to move! if(Input.GetMouseButtonDown(1)) { for (int a = 0; a < selCount; a++) { unitArr[a].SendMessage("Destination", hitPos.point); //if double-click same point, run! if (lastHit.point == hitPos.point) { unitArr[a].SendMessage("RunDude", 1); } } lastHit.point = hitPos.point; } //If L-click anything but an agent, deselects ALL agents if(hitPos.transform.tag != "Agent" && Input.GetMouseButtonDown(0)) { if(unitArr[0] != null) for (int a = 0; a < selCount; a++) unitArr[a].SendMessage("Deselect", 1); System.Array.Clear(unitArr, 0, selCount); selCount = 0; } } }
public void destroyed(GameObject o) { if (gameobjects.Contains(o)) { if (o.Equals(player)) { player = null; } if (o.name.ToLower().Contains("enemy")) { EnemyCount--; } gameobjects.Remove(o); } }
/* * Remove the provided enemy object from the player's list of enemies to track. */ public void ForgetEnemy(GameObject enemy) { if (enemies.Contains (enemy)) { bool sameAsTarget = enemy.Equals (fighter.target); enemies.Remove (enemy); if (sameAsTarget) { bool didRetarget = TargetNearest (); if (!didRetarget) { fighter.LoseTarget (); } } } else { Debug.LogWarning ("Tried to remove enemy from list in which it doesn't exist."); } }
public static void UpdateLight(GameObject selLight) { if (!selLight?.Equals(null) ?? false) { var _light = selLight; _light.GetOrAddComponent <MeshRenderer>().enabled = !Config.hideMeshRender; _light.GetOrAddComponent <VRC_Pickup>().orientation = Config.pickupOrient ? VRC_Pickup.PickupOrientation.Any : VRC_Pickup.PickupOrientation.Grip; _light.GetOrAddComponent <VRC_Pickup>().pickupable = Config.pickupable; _light.GetOrAddComponent <Light>().type = Config.lightType; // LightType.Point LightType.Directional LightType.Spot; _light.GetOrAddComponent <Light>().range = Config.lightRange; //Spot|Point _light.GetOrAddComponent <Light>().spotAngle = Config.lightSpotAngle; //Spot _light.GetOrAddComponent <Light>().color = Config.lightColor; _light.GetOrAddComponent <Light>().intensity = Config.lightIntensity; _light.GetOrAddComponent <Light>().shadows = Config.lightShadows; _light.GetOrAddComponent <Light>().shadowStrength = Config.lightShadowStr; _light.GetOrAddComponent <Light>().shadowCustomResolution = Config.lightShadowCustRes; } }
public static void LoadLightSettings(GameObject selLight) { if (!selLight?.Equals(null) ?? false) { var _light = selLight; Config.hideMeshRender = !_light.GetOrAddComponent <MeshRenderer>().enabled; Config.pickupOrient = (_light.GetOrAddComponent <VRC_Pickup>().orientation == VRC_Pickup.PickupOrientation.Any); Config.pickupable = _light.GetOrAddComponent <VRC_Pickup>().pickupable; Config.lightType = _light.GetOrAddComponent <Light>().type; Config.lightRange = _light.GetOrAddComponent <Light>().range; Config.lightSpotAngle = _light.GetOrAddComponent <Light>().spotAngle; Config.lightColor = _light.GetOrAddComponent <Light>().color; Config.lightIntensity = _light.GetOrAddComponent <Light>().intensity; Config.lightShadows = _light.GetOrAddComponent <Light>().shadows; Config.lightShadowStr = _light.GetOrAddComponent <Light>().shadowStrength; Config.lightShadowCustRes = _light.GetOrAddComponent <Light>().shadowCustomResolution; } }
void OnDied(GameObject enemy) { if (enemy.Equals (gameObject)) { StartCoroutine (StopSpinning (EnemyLife.deathTime)); if(dropMinionsOnDeath) { foreach(Transform t in transform.FindChild("Minions")) { t.parent = transform.parent; t.GetComponent<RandomMovement>().enabled = true; if(OnMinionReleased != null) OnMinionReleased(t.gameObject); } } } }
/** * Make object visible within range * * Arguments * - GameObject hiddenObject - The object to make visible */ void makeVisibleWithinRange(GameObject hiddenObject) { int distance; // The distance if (hiddenObject.Equals(gameObject)) return; // Skip over ourselves distance = MovementController.TileDistance( Player.MyPlayer.transform.position, hiddenObject.transform.position, Player.MyPlayer.GetComponent<MovementController>().GetBlockedTiles() ); if (distance <= Range) { // Within range if (hiddenObject.GetComponent<Stealth>().enabled) { hiddenObject.GetComponent<Stealth>().enabled = false; hiddenObject.GetComponentInChildren<MeshRenderer>().enabled = true; } } else { // Not within range if (!hiddenObject.GetComponent<Stealth>().enabled) hiddenObject.GetComponent<Stealth>().enabled = true; } }
public static void CleanupOneObject(GameObject obj, bool clearAsGo = true) { if (!obj?.Equals(null) ?? false) { //Logger.Msg("Removing Object"); if (clearAsGo) { lightList.Remove(obj); } UnityEngine.Object.Destroy(obj); if (textDic.TryGetValue(obj, out Texture2D tex)) { //Logger.Msg("Removing Texture"); textDic.Remove(obj); if (!tex?.Equals(null) ?? false) { UnityEngine.Object.Destroy(tex); } } } }
public Stack ShortestPath(GameObject start, GameObject end) { InitializeNodesForShortestPath(); start.GetComponent<NavpointScript>().SetDist(0f); SortedList nodes = new SortedList(); nodes.Add (0f, start); while(nodes.Count > 0){ if(end.Equals ((GameObject)nodes.GetByIndex (0))){ break; } NavpointScript u = ((GameObject)nodes.GetByIndex (0)).GetComponent<NavpointScript>(); nodes.RemoveAt (0); u.SetVisited(); GameObject[] adj = u.GetAdjacentNodes(); for(int i = 0; i < adj.Length; i++){ NavpointScript v = adj[i].GetComponent<NavpointScript>(); float alt = u.GetDistByIndex (i) + u.GetDist (); if(alt < v.GetDist () && !v.Visited ()){ v.SetDist(alt); v.SetPrev(u.gameObject); if(nodes.ContainsValue (v)) nodes.RemoveAt (nodes.IndexOfValue (v)); nodes.Add (alt, v.gameObject); } } } Stack s = new Stack(); GameObject node = end; while(node != null){ s.Push(node); node = node.GetComponent<NavpointScript>().GetPrev(); } return s; }
public void DisplayValue(GameObject updateEnemy, int newValue) { //Debug.Log(updateEnemy.name + ".cation=" + newValue); int maxValue = 0; if (!updateEnemy.Equals(maxCautionEnemy)) { // 同一でないなら現状のMax値を持つ敵の現在の値と比較 maxValue = GetCautionValue(maxCautionEnemy); if (newValue > maxValue) { maxValue = newValue; maxCautionEnemy = updateEnemy; } } else { // 同一ならそのまま更新 maxValue = newValue; } // 最大値を表示用に通知 if(ui)ui.BroadcastMessage("OnUpdateCaution", maxValue, SendMessageOptions.DontRequireReceiver); }
public void CheckSequence(GameObject nextObject) { if(nextObject.Equals(sequence[currIndex])){ gm.GiveNotice(1f, "Correct!"); currIndex++; //if end of sequence if(currIndex==sequenceLength){ gm.GiveNotice(1f, "Found the Key!"); currIndex=0; Instantiate(Key_door1); keyAud.Play(); CanCheckSequence=false; } }else{ gm.GiveNotice(4f, "Incorrect! Enemies will spawn soon."); currIndex=0; int rand = Mathf.RoundToInt(Random.Range(0, possibleEnemies.Length-1)); GameObject enemy = possibleEnemies[rand]; StartCoroutine(SpawnMonsters(enemy)); } }
public override void OnPreferencesSaved() { if (!n05?.Equals(null) ?? false) { n05.SetActive(!UIX_butts_QM.Value); } if (!n01?.Equals(null) ?? false) { n01.SetActive(!UIX_butts_QM.Value); } if (!n001?.Equals(null) ?? false) { n001.SetActive(!UIX_butts_QM.Value); } if (!n0001?.Equals(null) ?? false) { n0001.SetActive(!UIX_butts_QM.Value); } if (!QMbutt?.Equals(null) ?? false) { QMbutt.SetActive(UIX_butts_QM.Value); } }
public void DisplayDiscription(GameObject card, bool display) { Card cardScript = card.GetComponent<Card>(); if (display) { if (GameObject.Find("Card Hover") != null) { Destroy(GameObject.Find("Card Hover")); } GameObject hover = Instantiate((GameObject)Resources.Load("Prefabs/Card Hover")); hover.transform.SetParent(GameObject.Find("Canvas").transform); hover.transform.position = new Vector2(640,427); hover.transform.FindChild("Card").FindChild("Splash Image").GetComponent<Image>().sprite = card.transform.FindChild("Splash Image").GetComponent<Image>().sprite; hover.transform.FindChild("Card").FindChild("Card Frame").GetComponent<Image>().sprite = card.transform.FindChild("Card Frame").GetComponent<Image>().sprite; hover.transform.FindChild("Card").FindChild("Description").GetComponent<Text>().text = card.transform.FindChild("Description").GetComponent<Text>().text; hover.transform.FindChild("Card").FindChild("Title").GetComponent<Text>().text = card.transform.FindChild("Title").GetComponent<Text>().text; hover.transform.FindChild("Card").FindChild("Cost").GetComponent<Text>().text = card.transform.FindChild("Cost").GetComponent<Text>().text; hover.transform.FindChild("Card").FindChild("Attack").GetComponent<Text>().text = card.transform.FindChild("Attack").GetComponent<Text>().text; hover.transform.FindChild("Card").FindChild("Health").GetComponent<Text>().text = card.transform.FindChild("Health").GetComponent<Text>().text; hover.transform.FindChild("Card").FindChild("Defense").GetComponent<Text>().text = card.transform.FindChild("Defense").GetComponent<Text>().text; hover.transform.FindChild("Card").FindChild("Health").GetComponent<Text>().text = card.transform.FindChild("Health").GetComponent<Text>().text; hover.transform.FindChild("Card").FindChild("Range").GetComponent<Text>().text = card.transform.FindChild("Range").GetComponent<Text>().text; hover.name = "Card Hover"; foreach (GameObject c in GameObject.FindGameObjectsWithTag("Card")) { if (c.GetComponent<isDraggable>().displayZoomedView == true && !card.Equals(c)) { c.GetComponent<isDraggable>().displayZoomedView = false; Debug.Log("Display closed for " + c.name); } } } else if (!display && GameObject.Find("Card Hover") != null) { Destroy(GameObject.Find("Card Hover")); } }
// Update is called once per frame void Update() { mProjBody.transform.LookAt(mTargetBody.transform.position); if (mIsPickingTargetBody) { // update target position Vector3 newPos = mTargetBody.transform.position; if (Input.GetKey(KeyCode.A)) { newPos.x -= mMoveSpeed * Time.deltaTime; } if (Input.GetKey(KeyCode.D)) { newPos.x += mMoveSpeed * Time.deltaTime; } if (Input.GetKey(KeyCode.S)) { newPos.z -= mMoveSpeed * Time.deltaTime; } if (Input.GetKey(KeyCode.W)) { newPos.z += mMoveSpeed * Time.deltaTime; } if (Input.GetKey(KeyCode.F)) { newPos.y -= mMoveSpeed * Time.deltaTime; } if (Input.GetKey(KeyCode.R)) { newPos.y += mMoveSpeed * Time.deltaTime; } mTargetBody.transform.position = newPos; mTargetBody.GetComponentInChildren <Renderer>().material.color = Color.red; newLine = mProjBody.GetComponent <LineRenderer>(); newLine.SetPosition(1, mTargetBody.transform.position); } else { mTargetBody.GetComponentInChildren <Renderer>().material.color = Color.white; } if (mIsPickingProjBody) { // update target position Vector3 newPos = mProjBody.transform.position; if (Input.GetKey(KeyCode.A)) { newPos.x -= mMoveSpeed * Time.deltaTime; } ; if (Input.GetKey(KeyCode.D)) { newPos.x += mMoveSpeed * Time.deltaTime; } ; if (Input.GetKey(KeyCode.S)) { newPos.z -= mMoveSpeed * Time.deltaTime; } ; if (Input.GetKey(KeyCode.W)) { newPos.z += mMoveSpeed * Time.deltaTime; } ; if (Input.GetKey(KeyCode.F)) { newPos.y -= mMoveSpeed * Time.deltaTime; } ; if (Input.GetKey(KeyCode.R)) { newPos.y += mMoveSpeed * Time.deltaTime; } ; mProjBody.transform.position = newPos; for (int i = 0; i < mProjBody.transform.childCount; i++) { mProjBody.transform.GetChild(i).GetComponentInChildren <Renderer>().material.color = Color.red; } newLine = mProjBody.GetComponent <LineRenderer>(); newLine.SetPosition(0, mProjBody.transform.position); } else { for (int i = 0; i < mProjBody.transform.childCount; i++) { mProjBody.transform.GetChild(i).GetComponentInChildren <Renderer>().material.color = Color.white; } } // Picking code if (Input.GetMouseButtonDown(0)) { RaycastHit hit; Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition); if (Physics.Raycast(ray, out hit, 1000.0f)) { if (mProjBody.Equals(hit.transform.gameObject)) { mIsPickingProjBody = true; mIsPickingTargetBody = false; } else if (mTargetBody.Equals(hit.transform.gameObject)) { mIsPickingProjBody = false; mIsPickingTargetBody = true; } else { mIsPickingProjBody = mIsPickingTargetBody = false; } } else { mIsPickingProjBody = mIsPickingTargetBody = false; } } }
public bool HasEventFor(GameObject gameObject) { return(timedEventList.Exists(e => gameObject.Equals(e.GameObject))); }
void OnDied(GameObject enemy) { if(enemy.Equals(gameObject)) { myRigidbody2D.velocity = Vector2.zero; StartCoroutine(StopSpinning(EnemyLife.deathTime)); } }
void updateArmPosition(GameObject myo, ArmTransform armSegment, Quaternion _antiYaw, float _referenceRoll) { ThalmicMyo thalmicMyo = myo.GetComponent <ThalmicMyo> (); bool updateReference = false; if (myo.Equals(myoLower)) { // Update references when the pose becomes fingers spread or the q key is pressed. if (thalmicMyo.pose != _lastPose) { _lastPose = thalmicMyo.pose; if (thalmicMyo.pose == Pose.Fist) { updateReference = true; ExtendUnlockAndNotifyUserAction(thalmicMyo); } } if (Input.GetKeyDown("r")) { updateReference = true; } } // Update references. This anchors the joint on-screen such that it faces forward away // from the viewer when the Myo armband is oriented the way it is when these references are taken. if (updateReference) { _antiYawUpper = Quaternion.FromToRotation( new Vector3(myoUpper.transform.forward.x, myoUpper.transform.forward.y, myoUpper.transform.forward.z), new Vector3(1, 0, 0) ); // _referenceRoll represents how many degrees the Myo armband is rotated clockwise // about its forward axis (when looking down the wearer's arm towards their hand) from the reference zero // roll direction. This direction is calculated and explained below. When this reference is // taken, the joint will be rotated about its forward axis such that it faces upwards when // the roll value matches the reference. Vector3 referenceZeroRoll = computeZeroRollVector(myoUpper.transform.forward, myoUpper); _referenceRollUpper = rollFromZero(referenceZeroRoll, myoUpper.transform.forward, myoUpper.transform.up); // _antiYaw represents a rotation of the Myo armband about the Y axis (up) which aligns the forward // vector of the rotation with Z = 1 when the wearer's arm is pointing in the reference direction. _antiYawLower = Quaternion.FromToRotation( new Vector3(myoLower.transform.forward.x, 0, myoLower.transform.forward.z), new Vector3(1, 0, 0) ); _antiYaw = _antiYawLower; // _referenceRoll represents how many degrees the Myo armband is rotated clockwise // about its forward axis (when looking down the wearer's arm towards their hand) from the reference zero // roll direction. This direction is calculated and explained below. When this reference is // taken, the joint will be rotated about its forward axis such that it faces upwards when // the roll value matches the reference. referenceZeroRoll = computeZeroRollVector(myoLower.transform.forward, myoLower); _referenceRollLower = rollFromZero(referenceZeroRoll, myoLower.transform.forward, myoLower.transform.up); _referenceRoll = _referenceRollLower; } // Current zero roll vector and roll value. Vector3 zeroRoll = computeZeroRollVector(myo.transform.forward, myo); float roll = rollFromZero(zeroRoll, myo.transform.forward, myo.transform.up); // The relative roll is simply how much the current roll has changed relative to the reference roll. // adjustAngle simply keeps the resultant value within -180 to 180 degrees. float relativeRoll = normalizeAngle(roll - _referenceRoll); // antiRoll represents a rotation about the myo Armband's forward axis adjusting for reference roll. Quaternion antiRoll = Quaternion.AngleAxis(relativeRoll, myo.transform.forward); // Here the anti-roll and yaw rotations are applied to the myo Armband's forward direction to yield // the orientation of the joint. armSegment.transform.rotation = _antiYaw * antiRoll * Quaternion.LookRotation(myo.transform.forward); // The above calculations were done assuming the Myo armbands's +x direction, in its own coordinate system, // was facing toward the wearer's elbow. If the Myo armband is worn with its +x direction facing the other way, // the rotation needs to be updated to compensate. if (thalmicMyo.xDirection == Thalmic.Myo.XDirection.TowardWrist) { // Mirror the rotation around the XZ plane in Unity's coordinate system (XY plane in Myo's coordinate // system). This makes the rotation reflect the arm's orientation, rather than that of the Myo armband. armSegment.transform.rotation = new Quaternion(armSegment.transform.localRotation.x, -armSegment.transform.localRotation.y, armSegment.transform.localRotation.z, -armSegment.transform.localRotation.w); } }
/// <summary> /// Gets the player session using a UnityEngine.GameObject /// </summary> /// <param name="go"></param> /// <returns></returns> public PlayerSession FindSessionByGo(GameObject go) { var sessions = GameManager.Instance.GetSessions(); return((from i in sessions where go.Equals(i.Value.WorldPlayerEntity) select i.Value).FirstOrDefault()); }
void FixedUpdate() { if (_body.rigidbody.angularVelocity.magnitude < MIN_TORQUE_MAGNITUDE) { _body.renderer.material.color = Color.green; return; } else { _body.renderer.material.color = Color.red; } if (_lastMagnitude == 999) { _lastMagnitude = _body.rigidbody.angularVelocity.magnitude; return; } bool isIncreasing = (_body.rigidbody.angularVelocity.magnitude > _lastMagnitude); _lastMagnitudes[_lastMagnitudeIndex++] = Mathf.Abs(_lastMagnitude - _body.rigidbody.angularVelocity.magnitude); _lastMagnitudeIndex %= TOTAL_LAST_MAGNITUDES; _lastMagnitude = _body.rigidbody.angularVelocity.magnitude; // Debug.Log (_lastMagnitude); _timeToMotorSwitch -= Time.fixedDeltaTime; setMotorActive(_motorX, false, true); setMotorActive(_motorX2, false, true); setMotorActive(_motorY, false, true); setMotorActive(_motorZ, false, true); if (false == _stabilizing) { return; } if (isIncreasing) { if (_timeToMotorSwitch <= 0.0f) { _isForward = !_isForward; _timeToMotorSwitch = MinTimeBeforeMotorSwitchDirection; } } setMotorActive(_currentStabilizerMotor, true, _isForward); _timeToMotorChange -= Time.fixedDeltaTime; float sum = 0.0f; for (int i = 0; i < TOTAL_LAST_MAGNITUDES; i++) { sum += _lastMagnitudes[i]; } sum /= TOTAL_LAST_MAGNITUDES; if (sum < StableThreshold || _timeToMotorChange <= 0.0f) { if (_currentStabilizerMotor.Equals(_motorX)) { _currentStabilizerMotor = _motorY; } else if (_currentStabilizerMotor.Equals(_motorY)) { _currentStabilizerMotor = _motorZ; } else if (_currentStabilizerMotor.Equals(_motorZ)) { _currentStabilizerMotor = _motorX; } for (int i = 0; i < TOTAL_LAST_MAGNITUDES; i++) { _lastMagnitudes [i] = 9999; } _timeToMotorChange = MaxTimeBeforeMotorChange; } }
//Functions writing the gamedata files !!! Make sure that the order of the tags are matching the order of data points in the next function //Update function for monitoring and logging the gamestate //Contains helper lines for logging the summarized gameplay data private void FixedUpdate() { if (recordGameplay) { //Logs distance traveled for the gameplay summary currentPlaySession.distanceTraveled += (player.GetComponent <PlayerController>().transform.position - previousPlayerPosition).magnitude; previousPlayerPosition = player.GetComponent <PlayerController>().transform.position; currentPlaySession.agentDistanceTraveled += (agent.transform.position - previousAgentPosition).magnitude; previousAgentPosition = agent.transform.position; //Logs time spent on chasing the player bool agentInChase = false; bool targetSeen = false; if (!agent.Equals(null)) { targetSeen = (agent.GetComponent <ProximityDetector>().playerDetected || agent.GetComponent <FieldOfView>().targetDetected); agentInChase = agent.GetComponent <Movement>().targetLastSeen; if (agentInChase) { currentPlaySession.timeAgentWasAgressive += Time.deltaTime; } if (targetSeen) { currentPlaySession.timePlayerWasInSight += Time.deltaTime; } } //Construct row for report data List <string> rowData = new List <string>(); long epochTime = currentPlaySession.startByEpoch * 1000; int timeStep = Mathf.RoundToInt(Time.timeSinceLevelLoad * 1000); rowData.Add((epochTime + timeStep).ToString()); //TimeStamp rowData.Add(levelManager.score.ToString()); //CurrentScore if (!agent.Equals(null)) { rowData.Add(agent.transform.position.x.ToString()); //AgentPositionX rowData.Add(agent.transform.position.y.ToString()); //AgentPositionY rowData.Add(agent.transform.eulerAngles.z.ToString()); //AgentRotation rowData.Add(agent.GetComponent <Movement>().speed.ToString()); //AgentSpeed rowData.Add(agent.GetComponent <Movement>().rotationSpeed.ToString()); //AgentRotationSpeed rowData.Add(agent.GetComponent <FieldOfView>().viewAngle.ToString()); //AgentViewAngle rowData.Add(agent.GetComponent <FieldOfView>().viewRadius.ToString()); //AgentViewRadius rowData.Add((agent.GetComponent <Movement>().isWaiting ? 1 : 0).ToString()); //AgentSearching rowData.Add(agent.GetComponent <Movement>().lookAroundCycle.ToString()); //AgentSearchLength(turn#) rowData.Add(agent.GetComponent <ProximityDetector>().hearingRadius.ToString()); //AgentHearingRadius rowData.Add(agent.GetComponent <ProximityDetector>().detectionChance.ToString()); //AgentHearingProbability rowData.Add(agent.GetComponent <Health>().health.ToString()); //AgentHealth rowData.Add(agent.GetComponent <FrustrationComponent>().levelOfFrustration.ToString()); //AgentFrustration rowData.Add(agent.GetComponent <Movement>().riskTakingFactor.ToString()); //AgentRiskTakingFactor rowData.Add((agent.GetComponent <Movement>().takingRiskyPath ? 1 : 0).ToString()); //AgentTakingRiskyPath rowData.Add((targetSeen ? 1 : 0).ToString()); //AgentSeeingPlayer rowData.Add((agentInChase ? 1 : 0).ToString()); //AgentChasingPlayer } else { for (int i = 0; i < 17; i++) { rowData.Add("%AD%"); //Tag for "Agent Down". Still records the last actions of the Player before end level } } if (!agent.Equals(null) && !player.Equals(null)) //AgentDistanceFromPlayer { rowData.Add((new Vector2(agent.transform.position.x, agent.transform.position.y) - new Vector2(player.transform.position.x, player.transform.position.y)).magnitude.ToString()); } else { rowData.Add("%GO%"); //Tag for "Game Over". Still records inputs from the Player before end level } if (!player.Equals(null)) { rowData.Add(player.GetComponent <PlayerController>().transform.position.x.ToString()); //PlayerPositionX rowData.Add(player.GetComponent <PlayerController>().transform.position.y.ToString()); //PlayerPositionY rowData.Add(player.transform.eulerAngles.z.ToString()); //PlayerRotation rowData.Add(player.GetComponent <PlayerHealth>().health.ToString()); //PlayerHealth rowData.Add((player.GetComponent <PlayerController>().dashing ? 1 : 0).ToString()); //PlayerIsDashing rowData.Add((((Input.GetKeyDown(KeyCode.LeftShift) || Input.GetKeyDown(KeyCode.RightShift) || Input.GetKeyDown(KeyCode.Space)) && player.GetComponent <PlayerController>().dashOnCD) ? 1 : 0).ToString()); //PlayerTriesDashOnCD } else { for (int i = 0; i < 5; i++) { rowData.Add("%PD%"); //Tag for "Player Down". Still records inputs from the Player before end level } } rowData.Add(((Input.GetKeyDown(KeyCode.LeftShift) || Input.GetKeyDown(KeyCode.RightShift) || Input.GetKeyDown(KeyCode.Space)) ? 1 : 0).ToString()); //DashPressed rowData.Add(cursor.transform.position.x.ToString()); //CursorPositionX rowData.Add(cursor.transform.position.y.ToString()); //CursorPositionY rowData.Add((Input.GetMouseButton(0) && cursor.GetComponent <GunControls>().projectileCount == 0 ? 1 : 0).ToString()); //PlayerTriesToFireOnCD rowData.Add((Input.GetMouseButtonUp(1) && cursor.GetComponent <GunControls>().bombCount == 0 ? 1 : 0).ToString()); //PlayerTriesToBombOnCD rowData.Add((Input.GetMouseButton(0) && !cursor.GetComponent <GunControls>().reloading ? 1 : 0).ToString()); //ShotsFired rowData.Add((Input.GetMouseButtonUp(1) && !cursor.GetComponent <GunControls>().bombReloading ? 1 : 0).ToString()); //BombsDropped GameObject[] currentFires = GameObject.FindGameObjectsWithTag("fire"); int additonalItemsSpawned = currentFires.Length; if (additonalItemsSpawned > additionalItems) { additionalItems = additonalItemsSpawned; } rowData.Add(currentFires.Length.ToString()); //NumberOfActiveFires for (int i = 0; i < currentFires.Length; i++) //PositionOfActiveFires { rowData.Add(currentFires[i].transform.position.x.ToString()); rowData.Add(currentFires[i].transform.position.y.ToString()); } reportData.Enqueue(rowData); } }
private void Tool_Selection(Vector2 mouse) { if (Input.GetMouseButton(0)) { RaycastHit2D hit = Physics2D.Raycast(new Vector2(GetComponent <Camera>().ScreenToWorldPoint(Input.mousePosition).x, GetComponent <Camera>().ScreenToWorldPoint(Input.mousePosition).y), Vector2.zero, 0f); if (tools.interactive_tool.lever_tool.adding) { if (hit.collider != null && tools.interactive_tool.lever_tool.addable.Contains(hit.collider.name) && hit.collider.GetComponent <DependantPlatform>() != null) { tools.interactive_tool.lever_tool.adding = false; selection.GetComponent <Lever>().platforms.Add(hit.collider.GetComponent <DependantPlatform>().WhatIndexAmI()); } } else if (tools.interactive_tool.button_tool.adding) { if (hit.collider != null && tools.interactive_tool.button_tool.addable.Contains(hit.collider.name) && hit.collider.GetComponent <DependantPlatform>() != null) { tools.interactive_tool.button_tool.adding = false; selection.GetComponent <Button>().platforms.Add(hit.collider.GetComponent <DependantPlatform>().WhatIndexAmI()); } } else { if (!is_dragging && selection != null && hit.collider != null && selection.Equals(hit.collider.gameObject)) { is_dragging = true; } if (selection == null && hit.collider != null) { if (possible_selection.Contains(hit.collider.gameObject.name)) { selection = hit.collider.gameObject; //UnityEditor.Selection.objects = new GameObject[]{selection}; } } if (is_dragging) { selection.transform.position = new Vector3((Camera.main.ScreenToWorldPoint(Input.mousePosition).x - click_offset.x), (Camera.main.ScreenToWorldPoint(Input.mousePosition).y - click_offset.y), selection.transform.position.z); } } } else { is_dragging = false; if (selection != null) { selection.transform.position = new Vector3(Mathf.RoundToInt(selection.transform.position.x), Mathf.RoundToInt(selection.transform.position.y), selection.transform.position.z); } } if (Input.GetKey(KeyCode.Escape)) { if (tools.interactive_tool.lever_tool.adding) { tools.interactive_tool.lever_tool.adding = false; } else { selection = null; //UnityEditor.Selection.objects = new GameObject[0]; } } }
/// <summary> /// Gets the player session using a UnityEngine.GameObject /// </summary> /// <param name="go"></param> /// <returns></returns> public PlayerSession Find(GameObject go) { Dictionary <NetworkPlayer, PlayerSession> sessions = GameManager.Instance.GetSessions(); return((from i in sessions where go.Equals(i.Value.WorldPlayerEntity) select i.Value).FirstOrDefault()); }
/// <summary> /// Gets the player session using a UnityEngine.GameObject /// </summary> /// <param name="go"></param> /// <returns></returns> public PlayerSession Session(GameObject go) { return((from s in Sessions where go.Equals(s.Value.WorldPlayerEntity) select s.Value).FirstOrDefault()); }
public void BonusGem(GameObject gem) { for (int x = 0; x < gSizeX; x++) { for (int y = 0; y < gSizeY; y++) { if (gem.Equals(grid[x, y])) { bool wasBonused = false; if (bonusSelector.currentSelected == 0) { if (lu.grid[x, y].Gem.Bonus != (int)ParamUnit.Bonus.NONE) { wasBonused = true; if (lu.grid[x, y].Gem.Bonus == (int)ParamUnit.Bonus.COLORLESS || lu.grid[x, y].Gem.Bonus == (int)ParamUnit.Bonus.OBSTACLE) { lu.grid[x, y].Gem.Color = pu.GetRandomColor(); } lu.grid[x, y].Gem.Bonus = (int)ParamUnit.Bonus.NONE; } } else if (bonusSelector.currentSelected == 1) { if (lu.grid[x, y].Gem.Bonus != (int)ParamUnit.Bonus.ENERGY) { wasBonused = true; if (lu.grid[x, y].Gem.Bonus == (int)ParamUnit.Bonus.COLORLESS || lu.grid[x, y].Gem.Bonus == (int)ParamUnit.Bonus.OBSTACLE) { lu.grid[x, y].Gem.Color = pu.GetRandomColor(); } lu.grid[x, y].Gem.Bonus = (int)ParamUnit.Bonus.ENERGY; } } else { switch (pu.permittedBonuses[bonusSelector.currentSelected - 2]) { case (int)ParamUnit.Bonus.COLORLESS: lu.grid[x, y].Gem.Color = 8; break; case (int)ParamUnit.Bonus.OBSTACLE: lu.grid[x, y].Gem.Color = 9; break; default: if (lu.grid[x, y].Gem.Bonus == (int)ParamUnit.Bonus.COLORLESS || lu.grid[x, y].Gem.Bonus == (int)ParamUnit.Bonus.OBSTACLE) { lu.grid[x, y].Gem.Color = pu.GetRandomColor(); } break; } if (lu.grid[x, y].Gem.Bonus != pu.permittedBonuses[bonusSelector.currentSelected - 2]) { wasBonused = true; lu.grid[x, y].Gem.Bonus = pu.permittedBonuses[bonusSelector.currentSelected - 2]; } } if (wasBonused) { EditorParams.isSaved = false; DestroyGem(x, y, lu.grid[x, y].Gem.Color); SpawnGem(x, y, lu.grid[x, y].Gem.Color, lu.grid[x, y].Gem.Bonus, 0); } } } } }
/// <summary> /// Set the node where the camera will be attached to /// </summary> public void SetNode() { //Casts a ray from the camera in the direction the mouse is in and returns the closest object hit Ray ray = UnityEngine.Camera.main.ScreenPointToRay(UnityEngine.Input.mousePosition); BulletSharp.Math.Vector3 start = ray.origin.ToBullet(); BulletSharp.Math.Vector3 end = ray.GetPoint(200).ToBullet(); //Creates a callback result that will be updated if we do a ray test with it ClosestRayResultCallback rayResult = new ClosestRayResultCallback(ref start, ref end); //Retrieves the bullet physics world and does a ray test with the given coordinates and updates the callback object BPhysicsWorld world = BPhysicsWorld.Get(); world.world.RayTest(start, end, rayResult); //Debug.Log("Selected:" + rayResult.CollisionObject); //If there is a collision object and it is a robot part, set that to be new attachment point if (rayResult.CollisionObject != null) { GameObject selectedObject = ((BRigidBody)rayResult.CollisionObject.UserObject).gameObject; if (selectedObject.transform.parent != null && selectedObject.transform.parent.name == "Robot") { //Change highlight target when the mouse point to a different object if (lastNode != null && !selectedObject.Equals(lastNode)) { RevertNodeColors(lastNode, hoveredColors); lastNode = null; } //Highlight the node which mouse is pointing to to yellow else { ChangeNodeColors(selectedObject, hoverColor, hoveredColors); lastNode = selectedObject; } //Change the color to selected color when user click and choose the node if (UnityEngine.Input.GetMouseButtonDown(0)) { string name = selectedObject.name; //Revert the current selection back to its original so selectedColors can store the new selection properly RevertNodeColors(lastNode, hoveredColors); RevertNodeColors(SelectedNode, selectedColors); SelectedNode = selectedObject; ChangeNodeColors(SelectedNode, selectedColor, selectedColors); UserMessageManager.Dispatch(name + " has been selected as the node for camera attachment", 5); } } else { //When mouse is not pointing to any robot node, set the last hovered node back to its original color if (lastNode != null) { RevertNodeColors(lastNode, hoveredColors); lastNode = null; } //When users try to select a non-robotNode object if (UnityEngine.Input.GetMouseButtonDown(0)) { UserMessageManager.Dispatch("Please select a robot node!", 3); } } } }
//MOVE public override void Move() { //set speed to 10f speed = 5f; //attack range of the meleeunit attackRange = 20f; //if health less than 25%, run away //if (healthbar.value <= 0.25) //{ // //having them move back to run away // transform.Translate(Vector3.back * speed * Time.deltaTime); //} //creating a list of enemies to store units not on our team List <GameObject> enemies = new List <GameObject>(); //if the game object is not in in same team (gold in this case) then add to enemy list //will cycle through all 3 ifs until it finds one that is true if (!gameObject.CompareTag("Gold Team")) { foreach (GameObject u in GameObject.FindGameObjectsWithTag("Gold Team")) { enemies.Add(u); } } //same as above if (!gameObject.CompareTag("Green Team")) { foreach (GameObject u in GameObject.FindGameObjectsWithTag("Green Team")) { enemies.Add(u); } } //same as above if (!gameObject.CompareTag("Wizards")) { foreach (GameObject u in GameObject.FindGameObjectsWithTag("Wizards")) { enemies.Add(u); } } //finding closest unit pos GameObject closest = gameObject; float closestDistance = float.MaxValue; //foreach gamobj in the enemy list foreach (GameObject u in enemies) { //if distance is less than the closest dist if (Vector3.Distance(gameObject.transform.position, u.transform.position) < closestDistance) { //then this is the closest distance closestDistance = Vector3.Distance(gameObject.transform.position, u.transform.position); closest = u; } } //if the closests isnt the game obj itself if (!closest.Equals(gameObject)) { //look at the closest enemy transform.LookAt(closest.transform.position); //if they are not within att range if (closestDistance > attackRange) { //having them move forward transform.Translate(Vector3.forward * speed * Time.deltaTime); } //if they are within attack range else if (closestDistance <= attackRange) { //attaaack! Combat(closest); } } }
public override void onCharacterDie( GameObject character ) { if (character.Equals(player)){ isGameOver = true; } }
public override bool Equals(object obj) { return(obj is TransferTarget other && go != null && go.Equals(other.go)); }
public static Stack<GameObject> Dijkstra(GameObject start, GameObject end) { //Debug.Log (start.GetComponent<Node>().getConnections()); if(start.Equals(end)) { Stack<GameObject> temp = new Stack<GameObject>(); temp.Push(end); return temp; } List<GameObject> connections = new List<GameObject>(); GameObject endNode = start; float endNodeCost = 0; NodeRecord endNodeRecord = new NodeRecord(); NodeRecord startRecord = new NodeRecord(start, 0); List<NodeRecord> openList = new List<NodeRecord>(); List<NodeRecord> closedList = new List<NodeRecord>(); openList.Add(startRecord); NodeRecord current = startRecord; //Debug.Log (current); while(openList.Count > 0) { Debug.Log ("going through openlist"); current = getSmallestElement(openList); //Debug.Log (current); if(current.node.Equals(end)) { //Debug.Log ("Found goal"); break; } //Debug.Log("End not found contining"); connections = current.node.GetComponent<Node>().getConnections(); //Debug.Log ("Connections" + connections); foreach(GameObject connection in connections) { //Debug.Log(connection); endNode = connection.GetComponent<Connection>().toNode; endNodeCost = current.CostSoFar + connection.GetComponent<Connection>().cost + endNode.GetComponent<Node>().cost; if(isInList(endNode ,closedList)) { continue; } else if(isInList(endNode, openList)) { endNodeRecord = findNodeInList(endNode, openList); if(endNodeRecord.CostSoFar <= endNodeCost) { continue; } } else { endNodeRecord = new NodeRecord(endNode); } endNodeRecord.connection = connection; endNodeRecord.CostSoFar = endNodeCost; if(!(isInList (endNode, openList))) { openList.Add(endNodeRecord); } } openList.Remove(current); closedList.Add(current); } if(current.node != end) { return null; } else { Stack<GameObject> path = new Stack<GameObject>(); while(current.node != start) { path.Push(current.node); current = findNodeInList(current.connection.GetComponent<Connection>().fromNode, closedList); } return path; } }
void FixedUpdate() { if (switchObj.GetComponent <WeightSwitchActivator>().pressed) { if (propulsionHeight > 0) { rb.freezeRotation = true; transform.rotation = Quaternion.RotateTowards(transform.rotation, upAngle, 5); bool propping1 = false; bool propping2 = false; Vector2 start = getGroundVector(propulsionHeight); Debug.DrawLine(start, transform.position, Color.black); RaycastHit2D rch2d = Physics2D.Raycast(start, upDirection, propulsionHeight); if (rch2d && rch2d.collider != null) { GameObject ground = rch2d.collider.gameObject; if (ground != null && !ground.Equals(transform.gameObject)) { propping1 = true; } } start = getGroundVector((propulsionHeight + variance)); rch2d = Physics2D.Raycast(start, upDirection, propulsionHeight + variance); if (rch2d && rch2d.collider != null) { GameObject ground = rch2d.collider.gameObject; if (ground != null && !ground.Equals(transform.gameObject)) { propping2 = true; } } if (propping1 && propping2) { float heavyMultiplier = 1; float upVelocity = Vector3.Dot(rb.velocity, upDirection.normalized); if (upVelocity <= 0) { heavyMultiplier = forceMultiplierHeavy; } float force = liftForce * forceMultiplierSelf * heavyMultiplier; rb.AddForce(upDirection * force); } else if (!propping1 && propping2) { float heavyMultiplier = 1; float upVelocity = Vector3.Dot(rb.velocity, upDirection.normalized); if (upVelocity < 0) { heavyMultiplier = forceMultiplierHeavy; } else if (upVelocity > 0) { heavyMultiplier = 0; } rb.AddForce(upDirection * liftForce * forceMultiplierSteady * heavyMultiplier); } else { Debug.DrawLine(start, transform.position, Color.red); } } } else { rb.freezeRotation = false; } }
protected virtual void OnCollisionEnter(Collision collision) { if (!VRTK_PlayerObject.IsPlayerObject(collision.gameObject) && currentValidFloorObject != null && !currentValidFloorObject.Equals(collision.gameObject)) { CheckStepUpCollision(collision); currentCollidingObject = collision.gameObject; OnStartColliding(SetBodyPhysicsEvent(currentCollidingObject)); } }
/// <summary> /// Equips Items to the player /// </summary> public void EquipItem(GameObject _item) { //Check if player has this item if (!HasItem(_item)) { return; } //Item is armour piece if (_item.GetComponent <Armor>()) { //Set item into the correct slot if (_item.GetComponent <Armor>().armorType.Equals(Armor.ArmorType.ARMR_HELMET)) { //If the item we're trying to equip has already been equipped, then just return; if (playerHelmet.Equals(_item)) { return; } //If the item is different, then unequip the old armor UnEquipItem(playerHelmet); //Equip new armor playerHelmet = _item; } else if (_item.GetComponent <Armor>().armorType.Equals(Armor.ArmorType.ARMR_CHEST)) { //If the item we're trying to equip has already been equipped, then just return; if (playerChestplate.Equals(_item)) { return; } //If the item is different, then unequip the old armor UnEquipItem(playerChestplate); //Equip new armor playerChestplate = _item; } else if (_item.GetComponent <Armor>().armorType.Equals(Armor.ArmorType.ARMR_PANTS)) { //If the item we're trying to equip has already been equipped, then just return; if (playerPants.Equals(_item)) { return; } //If the item is different, then unequip the old armor UnEquipItem(playerPants); //Equip new armor playerPants = _item; } else if (_item.GetComponent <Armor>().armorType.Equals(Armor.ArmorType.ARMR_BOOTS)) { //If the item we're trying to equip has already been equipped, then just return; if (playerBoots.Equals(_item)) { return; } //If the item is different, then unequip the old armor UnEquipItem(playerBoots); //Equip new armor playerBoots = _item; } //Update player's defence stats ModifyCurrentDefence(_item.GetComponent <Armor>().armorDefence); } //Item is weapon if (_item.GetComponent <Weapon>()) { //If the item we're trying to equip has already been equipped, then just return; if (playerWeapon.Equals(_item)) { return; } //If the item is different, then unequip the old weapon UnEquipItem(playerWeapon); //Equip new weapon playerWeapon = _item; //Update player's attack stats ModifyCurrentAttack(_item.GetComponent <Weapon>().weaponDamage); } //Set item flag to be equipped _item.GetComponent <Item>().itemEquipped = true; }
protected void OnCollisionEnter(Collision collision) { if (!VRTK_PlayerObject.IsPlayerObject(collision.gameObject) && currentValidFloorObject && !currentValidFloorObject.Equals(collision.gameObject)) { currentCollidingObject = collision.gameObject; OnStartColliding(SetBodyPhysicsEvent(currentCollidingObject)); } }
public void VerifCase(int posX, int posY, int mouvement, int minDistAttack, int maxDistAttack) { if (maxDistAttack == 0) { return; } if (plateauDeJeux[posX, posY] == 1 && mouvement == 0) { FonctionRecu(posX, posY, 0, minDistAttack, maxDistAttack - 1); } GameObject objet = GetGameObject(posX, posY); if (objet != null && !selectedSquare.Equals(objet)) { if (objet.transform.Find("FloorBase").GetComponent <SpriteRenderer>().sprite != objet.GetComponent <Square>().inaccessibleSprite) { Character character = objet.GetComponent <Square>().GetCharacter(); if ((character != null && !IsEnemy(character.gameObject)) || character == null) { if (character != null && IsAlly(character.gameObject) && isMedecin == 1) { AddAlliesTiles(objet); } if (mouvement > 0) { if (character != null && !IsAlly(character.gameObject) || character == null || isMedecin == 0) { AddMovingTiles(objet); } FonctionRecu(posX, posY, mouvement - 1, minDistAttack, maxDistAttack); } else { if (minDistAttack <= DistanceEntrePoint((int)GetSelectedSquare().transform.position.x, (int)GetSelectedSquare().transform.position.y, posX, posY)) { if (objet.transform.Find("FloorBase").GetComponent <SpriteRenderer>().sprite != objet.GetComponent <Square>().inaccessibleSprite&& objet.transform.Find("FloorBase").GetComponent <SpriteRenderer>().sprite != objet.GetComponent <Square>().moveSprite&& objet.transform.Find("FloorBase").GetComponent <SpriteRenderer>().sprite != objet.GetComponent <Square>().alliesSprite) { AddMovingAttack(objet); } } FonctionRecu(posX, posY, 0, minDistAttack, maxDistAttack - 1); } } else { if (mouvement > 0) { AddMovingAttack(objet); } else { if (DistanceEntrePoint(posX, posY, (int)GetSelectedSquare().transform.position.x, (int)GetSelectedSquare().transform.position.y) >= minDistAttack) { AddMovingAttack(objet); } } if (maxDistAttack > 1) { FonctionRecu(posX, posY, 0, minDistAttack, maxDistAttack - 1); } } } else { if (maxDistAttack > 1) { FonctionRecu(posX, posY, 0, minDistAttack, maxDistAttack - 1); } } } }
public void CheckGaze() { //Send out a ray from the main camera's forward direction RaycastHit gazeHit = new RaycastHit(); Ray cameraRay = new Ray(Camera.main.transform.position, Camera.main.transform.forward); Debug.DrawRay(Camera.main.transform.position, Camera.main.transform.forward, Color.red, 10f); bool rayHit = Physics.Raycast(cameraRay, out gazeHit); //Check if the camera is looking at the same object as it was in the previous frame bool sameFocusAsPrevious = rayHit && gazeHit.transform.gameObject.Equals(focusedGazeObject); //If looking at the same object increment gazeTime by the elapsed time since last frame if (sameFocusAsPrevious) { gazeTime += Time.deltaTime; } //If focus has changed reset to new target if (rayHit && !sameFocusAsPrevious) { //Debug.Log ("Not Same as previous"); gazeTime = 0; focusedGazeObject = gazeHit.transform.gameObject; } //Only activate gaze once threshold reached and if object hasn't already been activated if (sameFocusAsPrevious && gazeTime > gazeThreshold && !focusedGazeObject.Equals(previousActivatedGazeObject)) { Debug.Log("Gaze Activated"); //focusedGazeObject.GetComponent<Renderer>().material.color = Color.blue; //Light to highlight the original //light.transform.position = focusedGazeObject.transform.position; //light.SetActive(true); //Set Text Label Position pageLabel.transform.position = focusedGazeObject.transform.position; pageLabel.transform.position = (Camera.main.transform.forward * -1 * 20 + pageLabel.transform.position); pageLabel.transform.LookAt(Camera.main.transform); pageLabel.transform.Rotate(new Vector3(0f, 180f, 0f)); //Update the pageLabel with the page title var textLabel = pageLabel.GetComponent <Text>(); textLabel.text = focusedGazeObject.GetComponent <StorePage>().data.pagetitle; //reset gaze gazeTime = 0; //Push Back the previous Page if (previousActivatedGazeObject != null) { previousActivatedGazeObject.transform.position = previousPosition; //(Camera.main.transform.forward * pullForwardForce + previousActivatedGazeObject.transform.position); } //Pull Selected Page Forward previousPosition = focusedGazeObject.transform.position; focusedGazeObject.transform.position = (Camera.main.transform.forward * -1 * pullForwardForce + focusedGazeObject.transform.position); //Debug.DrawRay (focusedGazeObject.transform.position, focusedGazeObject.transform.right, Color.red, 10f); //Debug.DrawRay (focusedGazeObject.transform.position, focusedGazeObject.transform.forward, Color.blue, 10f); //Debug.DrawRay (focusedGazeObject.transform.position, focusedGazeObject.transform.up, Color.green, 10f); //Save the current gaze object as the previous (to avoid reactivating the current object) previousActivatedGazeObject = focusedGazeObject; //-------------- Update Graph -------------------------- try { Page wikiPage = (Page)focusedGazeObject.GetComponent <StorePage>().data; Debug.Log(wikiPage); GenerateVisualization.UpdateGraph(wikiPage); }catch (MissingComponentException e) { Debug.Log("Could not find Page component of the focused object"); } } }
public int GetCubeTileIndex(GameObject cube) { for (int i = 0; i < Tiles.Length; i++) { Tile tile = Tiles[i]; if (cube.Equals(tile.Go)) { return tile.Id; } } Debug.LogError("Could not find Cube in Tiles."); return -1; }
private static bool CheckIfSelected(GameObject obj) { return(obj.Equals(selectedGameObject)); }
private void OnTriggerEnter(Collider other) { int layer = (int)Mathf.Pow(2, other.gameObject.layer); if (layerMaks.value == (layerMaks.value | layer)) { IDataInfoType iDataInfoType = other.gameObject.GetComponent <IDataInfoType>(); if (iDataInfoType != null) { if (!GameObject.Equals(nowObj, other.gameObject)) { GameObject lastObj = nowObj; nowObj = other.gameObject; IPlayerState iPlayerState = GameState.Instance.GetEntity <IPlayerState>(); if (Type.Equals(iDataInfoType.T, typeof(StuffDataInfoMono))) { StuffDataInfoMono stuffDataInfoMono = iDataInfoType as StuffDataInfoMono; if (stuffDataInfoMono.StuffDataInfo.ResidualCount() <= 0) { //尝试刷新 stuffDataInfoMono.StuffDataInfo.Update(); } //如果大于零则表示可以 if (stuffDataInfoMono.StuffDataInfo.ResidualCount() > 0) { iPlayerState.TouchTargetStruct = new TouchTargetStruct() { ID = stuffDataInfoMono.StuffDataInfo.StuffID, TerrainName = stuffDataInfoMono.StuffDataInfo.SceneName, TouchTargetType = TouchTargetStruct.EnumTouchTargetType.Stuff }; } else { nowObj = lastObj; } } else if (Type.Equals(iDataInfoType.T, typeof(NPCDataInfoMono))) { NPCDataInfoMono npcDataInfoMono = iDataInfoType as NPCDataInfoMono; iPlayerState.TouchTargetStruct = new TouchTargetStruct() { ID = npcDataInfoMono.NPCDataInfo.NPCID, TerrainName = npcDataInfoMono.NPCDataInfo.SceneName, TouchTargetType = TouchTargetStruct.EnumTouchTargetType.NPC }; } else if (Type.Equals(iDataInfoType.T, typeof(ActionInteractiveDataInfoMono))) { ActionInteractiveDataInfoMono actionInteractiveDataInfoMono = iDataInfoType as ActionInteractiveDataInfoMono; iPlayerState.TouchTargetStruct = new TouchTargetStruct() { ID = actionInteractiveDataInfoMono.ActionInteractiveDataInfo.ActionInteractiveID, TerrainName = actionInteractiveDataInfoMono.ActionInteractiveDataInfo.SceneName, TouchTargetType = TouchTargetStruct.EnumTouchTargetType.Action }; } } } } }
private void OnTriggerStay(Collider other) { if ((other.gameObject.layer == LayerMask.NameToLayer("TrapOverlap") || other.tag == "Platform" || other.tag == "Trigger4") && !GameObject.Equals(this.transform.parent, other.transform.parent)) { nearbyTrap = true; } }
// Update is called once per frame void Update() { if (target == null) { return; } if (original_magnitude == 0) { original_magnitude = (target.transform.position - gameObject.transform.position).magnitude; speed = original_magnitude / GetComponent <Spell>().effectTime; } Vector3 displacement = (target.transform.position - gameObject.transform.position); Vector3 dir = displacement.normalized; trajectoryHeight = SceneData.sceneData.ground.SampleHeight(transform.position); Velocity = displacement.normalized * speed; //speed = displacement.magnitude / GetComponent<Spell>().effectTime; prev_speed = displacement.magnitude / GetComponent <Spell>().effectTime; // Check for all units nearby if (displacement.sqrMagnitude < 10 * 10) { List <GameObject> nearbylist = SpatialPartition.instance.GetObjectListAt(transform.position); for (int i = 0; i < nearbylist.Count; ++i) { if (!nearbylist[i]) // if not a unit { continue; } // Unit/building takes damage from spell GameObject building = nearbylist[i]; if (nearbylist[i].GetComponent <Unit>()) { if (!nearbylist[i].GetComponent <Unit>().m_isFriendly&& !m_run) { nearbylist[i].GetComponent <Unit>().TakeDamage(damage); } } if (building.GetComponent <Building>() && !building.Equals(LevelManager.instance.PlayerBase)) { if (!nearbylist[i].GetComponent <Building>().isfriendly&& !m_run) { nearbylist[i].GetComponent <Building>().TakeDamage(damage); } } if (i == nearbylist.Count - 1) { m_run = true; } } if (GetComponent <Spell>().effectTimer.can_run) { ParticleSystem ps = gameObject.transform.GetChild(1).gameObject.GetComponent <ParticleSystem>(); if (!ps.isPlaying) { ps.transform.position = new Vector3(target.transform.position.x, target.transform.position.y, target.transform.position.z); ps.gameObject.SetActive(true); ps.Play(); } } } gameObject.transform.position += Velocity * Time.deltaTime; // Arc float cTime = displacement.magnitude; // calculate straight-line lerp position: Vector3 currentPos = Vector3.Lerp(LevelManager.instance.PlayerBase.transform.position, target.transform.position, cTime); // add a value to Y, using Sine to give a curved trajectory in the Y direction transform.position = new Vector3(transform.position.x, prev_speed + currentPos.y + (SceneData.sceneData.ground.terrainData.size.y * Mathf.Sin(Mathf.Clamp01(cTime) * Mathf.PI)), transform.position.z); //create the rotation we need to be in to look at the target lookRotation = Quaternion.LookRotation(dir); transform.rotation = Quaternion.Slerp(transform.rotation, lookRotation, Time.deltaTime * 5); }