// public override void Start() // { // base.Start(); // // player = FindObjectOfType<Player>().transform; // spawner = GetComponent<Spawner>(); // // direction = UpdatePath(); // // currentState = State.Chasing; // } public override void Update() { base.Update(); //if (GameController.Instance.listObject.Count > 1) //{ switch (UIManager.Ins.gamePlay.typeAI) { case TypeAI.SizeBall: if (ballKeeping != null && isMoved) { if (ballKeeping.compareSize(sizeBall)) { ReleaseBall(); target = null; SetRandomState(); } else if (target == null) { direction = UpdatePath(); } } break; case TypeAI.DirectionToTarget: if (direction == Vector3.zero) { direction = UpdatePath(); } else if (transform.up.normalized == direction.normalized) { ReleaseBall(); direction = UpdatePath(); SetRandomState(); } break; case TypeAI.FollowDirectionInTime: if (Time.time >= timeFollow) { ReleaseBall(); timeRandomFollow = Random.Range(2f, 7.5f); timeFollow = Time.time + timeRandomFollow; direction = new Vector3(Random.Range(-359, 359), Random.Range(-359, 359), 0); SetRandomState(); } break; case TypeAI.FollowTargetInTime: if (Time.time >= timeFollow) { ReleaseBall(); timeRandomFollow = Random.Range(2f, 7.5f); timeFollow = Time.time + timeRandomFollow; direction = UpdatePath(); SetRandomState(); } break; case TypeAI.SmartAI: if (Time.time >= timeFollow) { ReleaseBall(); timeRandomFollow = Random.Range(2f, 7.5f); timeFollow = Time.time + timeRandomFollow; direction = UpdatePath(); SetRandomState(); } break; } //} hitCommingGroundUp = Physics2D.Raycast(transform.position, transform.up, 100f, commingGround); hitCommingGroundDown = Physics2D.Raycast(transform.position, -transform.up, 100f, commingGround); if (Vector2.Distance(transform.position, hit.point) < 1.5f && currentState == StatusState.Chasing) { // SetRandomState(); direction = UpdatePath(); } else if (Vector2.Distance(transform.position, hit.point) < 0.5f && currentState == StatusState.Stun) { currentState = StatusState.Idle; } if (checkObjectOnGround()) { direction = UpdatePathForCommingGround(); } }
//Check for collisions with other cubes public static void CollisionCheck(GameObject cube, int playerNum) { Cube cubeObj = cube.GetComponent <Cube>(); //4 Cases: Horizontal, Vertical, Diagonal - Backslash, Diagonal - Forward slash //Horizontal - Left RaycastHit2D leftInfo = Physics2D.Raycast(cube.transform.position - horzOffset, Vector2.left, 0.05f); if (leftInfo && leftInfo.transform.gameObject.CompareTag(cube.tag)) { cubeObj.left = leftInfo.transform.gameObject; } //Horizontal - Right RaycastHit2D rightInfo = Physics2D.Raycast(cube.transform.position + horzOffset, Vector2.right, 0.05f); if (rightInfo && rightInfo.transform.gameObject.CompareTag(cube.tag)) { cubeObj.right = rightInfo.transform.gameObject; } //Check for 3 horizontal adjacents if (cubeObj.left && cubeObj.right) { cubeObj.bingoHorz = true; } //Vertical - Up RaycastHit2D upInfo = Physics2D.Raycast(cube.transform.position + vertOffset, Vector2.up, 0.05f); if (upInfo && upInfo.transform.gameObject.CompareTag(cube.tag)) { cubeObj.up = upInfo.transform.gameObject; } //Vertical - Down RaycastHit2D downInfo = Physics2D.Raycast(cube.transform.position - vertOffset, Vector2.down, 0.05f); if (downInfo && downInfo.transform.gameObject.CompareTag(cube.tag)) { cubeObj.down = downInfo.transform.gameObject; } //Check for 3 vertical adjacents if (cubeObj.up && cubeObj.down) { cubeObj.bingoVert = true; } //Diagonal - Backslash - Up Left RaycastHit2D upLeftInfo = Physics2D.Raycast(cube.transform.position + vertOffset - horzOffset, Vector2.up + Vector2.left, 0.05f); if (upLeftInfo && upLeftInfo.transform.gameObject.CompareTag(cube.tag)) { cubeObj.upLeft = upLeftInfo.transform.gameObject; } //Diagonal - Backslash - Down Right RaycastHit2D downRightInfo = Physics2D.Raycast(cube.transform.position - vertOffset + horzOffset, Vector2.down + Vector2.right, 0.05f); if (downRightInfo && downRightInfo.transform.gameObject.CompareTag(cube.tag)) { cubeObj.downRight = downRightInfo.transform.gameObject; } //Check for 3 backslash diagonal adjacents if (cubeObj.upLeft && cubeObj.downRight) { cubeObj.bingoBslash = true; } //Diagonal - Forward slash - Up Right RaycastHit2D upRightInfo = Physics2D.Raycast(cube.transform.position + vertOffset + horzOffset, Vector2.up + Vector2.right, 0.05f); if (upRightInfo && upRightInfo.transform.gameObject.CompareTag(cube.tag)) { cubeObj.upRight = upRightInfo.transform.gameObject; } //Diagonal - Forward slash - Down Left RaycastHit2D downLeftInfo = Physics2D.Raycast(cube.transform.position - vertOffset - horzOffset, Vector2.down + Vector2.left, 0.05f); if (downLeftInfo && downLeftInfo.transform.gameObject.CompareTag(cube.tag)) { cubeObj.downLeft = downLeftInfo.transform.gameObject; } //Check for 3 backslash diagonal adjacents if (cubeObj.upRight && cubeObj.downLeft) { cubeObj.bingoFslash = true; } cubeObj.didCollisionCheck = true; if (cubeObj.bingoHorz || cubeObj.bingoVert || cubeObj.bingoBslash || cubeObj.bingoFslash) { cubeObj.gotMatched = true; BoardManager.Instance.matcheds[playerNum] = true; if (!BoardManager.Instance.toBeDestroyeds[playerNum].Contains(cube)) { BoardManager.Instance.toBeDestroyeds[playerNum].Add(cube); } //Matched(cube); } }
// called when character motor ray is touching us override public bool OnCharacterTouch(APCharacterController character, APCharacterMotor.RayType rayType, RaycastHit2D hit, float penetration, APMaterial hitMaterial) { // Do nothing if dead if (IsDead()) { return(false); } // Do nothing in godmode APSamplePlayer samplePlayer = character.GetComponent <APSamplePlayer>(); if (samplePlayer && samplePlayer.IsGodModeEnabled()) { return(false); } // check if jumping on us bool bHit = false; if ((rayType == APCharacterMotor.RayType.Ground) && (penetration <= m_jumpHitPenetrationTolerance)) { // make character jump float fRatio = m_jumpRatioInputReleased; if (character.m_jump.m_button.IsSpecified() && character.m_jump.m_button.GetButton()) { fRatio = m_jumpRatioInputPushed; } if (fRatio > 0f) { character.Jump(character.m_jump.m_minHeight * fRatio, character.m_jump.m_maxHeight * fRatio); } // add hit to NPC if (samplePlayer) { AddHitDamage(samplePlayer.m_jumpDamage); } bHit = true; } else if (penetration <= m_hitPenetrationTolerance) { // add hit to character if (samplePlayer) { samplePlayer.OnHit(m_touchDamage, transform.position); } bHit = true; } // prevent checking hits too often if (bHit) { if (Time.time < m_lastHitTime + m_minTimeBetweenTwoReceivedHits) { return(false); } // save current hit time m_lastHitTime = Time.time; } // always ignore contact return(false); }
void Update() { if (endFlag) { if (Input.GetMouseButtonDown(0))// && Input.touchCount == 1) { startFlag = false; hit = Physics2D.Raycast(Camera.main.ScreenToWorldPoint(Input.mousePosition), Vector2.zero); ballPos = ballMove.getBallPos(); playerPref = PlayerPrefs.GetInt("Hint"); remainingNum = ballMove.RemainingNum; if (hit) { if (hit.transform.tag.Equals(Ball)) { startFlag = true; createLine(); } } } if (Input.GetMouseButton(0) && startFlag) { increase = 0; currentPos = Camera.main.ScreenToWorldPoint(Input.mousePosition); currentPos.z = 0; firstPos = ballPos + (currentPos - ballPos).normalized * 0.87f; ray = Physics2D.CircleCast(firstPos, 0.435f, (currentPos - ballPos).normalized, Mathf.Infinity); rayVector = ray.point + ray.normal * 0.435f; rayVector.z = 0; // Debug.DrawRay(firstPos, (rayVector-firstPos), Color.green); line.SetPosition(0, firstPos - (currentPos - ballPos).normalized * 0.87f); line.SetPosition(1, rayVector); if (playerPref.Equals(1)) { line.positionCount = remainingNum + 2; for (int i = 2; i < remainingNum + 2 + increase; i++) { reflect = Vector3.Reflect((rayVector - firstPos).normalized, ray.normal); if (Portal != null) { if (ray) { if (ray.transform.tag.Equals(PortalE)) { increase++; line.positionCount += 2; reflect = (rayVector - firstPos); rayVector = new Vector3(Portal.transform.position.x + 0.5f, Portal.transform.position.y, 0); line.SetPosition(i, rayVector); } } } if (Tunnel != null) { if (ray) { if (ray.transform.tag.Equals(TunnelE)) { increase++; line.positionCount += 2; reflect = (ExitT.transform.position - Tunnel.transform.position); rayVector = new Vector3(ExitT.transform.position.x, ExitT.transform.position.y, 0); line.SetPosition(i, rayVector); } } } ray = Physics2D.CircleCast(rayVector, 0.435f, reflect.normalized, Mathf.Infinity, 1 << 0); firstPos = rayVector; rayVector = ray.point + ray.normal * 0.435f; rayVector.z = 0; // Debug.DrawRay(firstPos, (rayVector - firstPos), Color.green); line.SetPosition(i + increase, rayVector); if (ray) { if (ray.transform.tag.Equals(Destination)) { line.positionCount = i + increase + 1; break; } } } } } if (Input.GetMouseButtonUp(0) && startFlag)// && Input.touchCount == 1) { endPos = Camera.main.ScreenToWorldPoint(Input.mousePosition); ballMove.MoveValueSet(endPos); ballMove.MoveFlagSet(true); endFlag = false; line.gameObject.SetActive(false); line = null; } } }
//-------------------------------------------------------------------- //-------------------------------------------------------------------- //-------------------------------------------------------------------- // Update is called once per frame void Update() { if (Input.GetMouseButtonDown(0)) { Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition); RaycastHit2D hit = Physics2D.Raycast(ray.origin, ray.direction); if (mode == "convey") { if (hit && hit.collider.gameObject.name.Contains("tempTile")) { GameObject.Find("Money").SendMessage("Earned", conveyCost); print(hit.collider.name); //StartCoroutine(conveyRotate()); Vector3 center = hit.collider.gameObject.transform.position; Destroy(hit.collider.gameObject); GameObject newTile = (GameObject)Instantiate(tileTexture, transform); newTile.name = "Convey (Up)" + newCounter; GameObject.Find(newTile.name).SendMessage("Direction", "Up"); newCounter++; newTile.transform.position = center; GameObject.Find(newTile.name).SendMessage("Direction", "Up"); } else if (hit && hit.collider.gameObject.name.Contains("Convey (Up)")) { print(hit.collider.name); //StartCoroutine(conveyRotate()); Vector3 center = hit.collider.gameObject.transform.position; Destroy(hit.collider.gameObject); GameObject newTile = (GameObject)Instantiate(tileTexture, transform); newTile.name = "Convey (Right)" + newCounter; newCounter++; newTile.transform.position = center; GameObject.Find(newTile.name).SendMessage("Direction", "Right"); } else if (hit && hit.collider.gameObject.name.Contains("Convey (Right)")) { print(hit.collider.name); //StartCoroutine(conveyRotate()); Vector3 center = hit.collider.gameObject.transform.position; Destroy(hit.collider.gameObject); GameObject newTile = (GameObject)Instantiate(tileTexture, transform); newTile.name = "Convey (Down)" + newCounter; newCounter++; newTile.transform.position = center; GameObject.Find(newTile.name).SendMessage("Direction", "Down"); } else if (hit && hit.collider.gameObject.name.Contains("Convey (Down)")) { print(hit.collider.name); //StartCoroutine(conveyRotate()); Vector3 center = hit.collider.gameObject.transform.position; Destroy(hit.collider.gameObject); GameObject newTile = (GameObject)Instantiate(tileTexture, transform); newTile.name = "Convey (Left)" + newCounter; newCounter++; newTile.transform.position = center; GameObject.Find(newTile.name).SendMessage("Direction", "Left"); } else if (hit && hit.collider.gameObject.name.Contains("Convey (Left)")) { print(hit.collider.name); Vector3 center = hit.collider.gameObject.transform.position; Destroy(hit.collider.gameObject); GameObject newTile = (GameObject)Instantiate(blankSpace, transform); newTile.name = "tempTile"; newCounter++; newTile.transform.position = center; } } else if (mode == "sort") { if (hit && hit.collider.gameObject.name.Contains("tempTile")) { GameObject.Find("Money").SendMessage("Earned", sortCost); print(hit.collider.name); //StartCoroutine(conveyRotate()); Vector3 center = hit.collider.gameObject.transform.position; Destroy(hit.collider.gameObject); GameObject newTile = (GameObject)Instantiate(Sorter, transform); newTile.name = "Sorter" + newCounter; newCounter++; newTile.transform.position = center; } else if (hit && hit.collider.gameObject.name.Contains("Sorter")) { print(hit.collider.name); Vector3 center = hit.collider.gameObject.transform.position; Destroy(hit.collider.gameObject); GameObject newTile = (GameObject)Instantiate(blankSpace, transform); newTile.name = "tempTile"; newCounter++; newTile.transform.position = center; } } else if (mode == "trash") { if (hit && hit.collider.gameObject.name.Contains("tempTile")) { GameObject.Find("Money").SendMessage("Earned", binCost); print(hit.collider.name); //StartCoroutine(conveyRotate()); Vector3 center = hit.collider.gameObject.transform.position; Destroy(hit.collider.gameObject); GameObject newTile = (GameObject)Instantiate(trashDump, transform); newTile.name = "trashDump" + newCounter; newCounter++; newTile.transform.position = center; } else if (hit && hit.collider.gameObject.name.Contains("trashDump")) { print(hit.collider.name); Vector3 center = hit.collider.gameObject.transform.position; Destroy(hit.collider.gameObject); GameObject newTile = (GameObject)Instantiate(blankSpace, transform); newTile.name = "tempTile"; newCounter++; newTile.transform.position = center; } } else if (mode == "recycling") { if (hit && hit.collider.gameObject.name.Contains("tempTile")) { GameObject.Find("Money").SendMessage("Earned", binCost); print(hit.collider.name); //StartCoroutine(conveyRotate()); Vector3 center = hit.collider.gameObject.transform.position; Destroy(hit.collider.gameObject); GameObject newTile = (GameObject)Instantiate(recycleDump, transform); newTile.name = "recycleDump" + newCounter; newCounter++; newTile.transform.position = center; } else if (hit && hit.collider.gameObject.name.Contains("recycleDump")) { print(hit.collider.name); Vector3 center = hit.collider.gameObject.transform.position; Destroy(hit.collider.gameObject); GameObject newTile = (GameObject)Instantiate(blankSpace, transform); newTile.name = "tempTile"; newCounter++; newTile.transform.position = center; } } //-------------------------------------------------------------------------------------------------------------------------------------- // -------------------------------------------------------------------------------------------------------------------------------------- // -------------------------------------------------------------------------------------------------------------------------------------- /* * if (hit && hit.collider.gameObject.name.Contains("tempTile")) * { * print(hit.collider.name); * * //StartCoroutine(conveyRotate()); * Vector3 center = hit.collider.gameObject.transform.position; * Destroy(hit.collider.gameObject); * GameObject newTile = (GameObject)Instantiate(tileTexture, transform); * * newTile.name = "Convey (Up)" + newCounter; * GameObject.Find(newTile.name).SendMessage("Direction", "Up"); * * newCounter++; * newTile.transform.position = center; * GameObject.Find(newTile.name).SendMessage("Direction", "Up"); * * } else if (hit && hit.collider.gameObject.name.Contains("Convey (Up)")){ * print(hit.collider.name); * * //StartCoroutine(conveyRotate()); * Vector3 center = hit.collider.gameObject.transform.position; * Destroy(hit.collider.gameObject); * GameObject newTile = (GameObject)Instantiate(tileTexture, transform); * * newTile.name = "Convey (Right)" + newCounter; * * newCounter++; * newTile.transform.position = center; * GameObject.Find(newTile.name).SendMessage("Direction", "Right"); * * * } else if (hit && hit.collider.gameObject.name.Contains("Convey (Right)")) * { * print(hit.collider.name); * * //StartCoroutine(conveyRotate()); * Vector3 center = hit.collider.gameObject.transform.position; * Destroy(hit.collider.gameObject); * GameObject newTile = (GameObject)Instantiate(tileTexture, transform); * * newTile.name = "Convey (Down)" + newCounter; * //GameObject.Find(newTile.name).SendMessage("Direction", "Down"); * //newTile.name = "newTile"; * newCounter++; * newTile.transform.position = center; * GameObject.Find(newTile.name).SendMessage("Direction", "Down"); * * * } else if (hit && hit.collider.gameObject.name.Contains("Convey (Down)")) * { * print(hit.collider.name); * * //StartCoroutine(conveyRotate()); * Vector3 center = hit.collider.gameObject.transform.position; * Destroy(hit.collider.gameObject); * GameObject newTile = (GameObject)Instantiate(tileTexture, transform); * * newTile.name = "Convey (Left)" + newCounter; * * newCounter++; * newTile.transform.position = center; * GameObject.Find(newTile.name).SendMessage("Direction", "Left"); * * * } else if (hit && hit.collider.gameObject.name.Contains("Convey (Left)")) * { * print(hit.collider.name); * * //StartCoroutine(conveyRotate()); * Vector3 center = hit.collider.gameObject.transform.position; * Destroy(hit.collider.gameObject); * GameObject newTile = (GameObject)Instantiate(Sorter, transform); * * newTile.name = "Sorter" + newCounter; * * newCounter++; * newTile.transform.position = center; * * * } else if (hit && hit.collider.gameObject.name.Contains("Sorter")) * { * print(hit.collider.name); * * Vector3 center = hit.collider.gameObject.transform.position; * Destroy(hit.collider.gameObject); * GameObject newTile = (GameObject)Instantiate(blankSpace, transform); * newTile.name = "tempTile"; * newCounter++; * newTile.transform.position = center; * * } */ } }
/** * This function will detect when the user clicks on the left mouse button, * and cast a ray into the 2d plane. It will check if the user has clicked * on a puzzle piece. If true, it will then check if the empty space is * next to piece the user clicked on. If that is true, the piece will swap * with the empty piece. */ private void CheckInput() { if (Input.GetMouseButtonDown(0)) { Ray r = Camera.main.ScreenPointToRay(Input.mousePosition); RaycastHit2D hit = Physics2D.Raycast(r.origin, r.direction); if (hit.collider != null) { string[] parts = hit.collider.gameObject.name.Split('-'); int rowPart = int.Parse(parts[1]); int colPart = int.Parse(parts[2]); int rowFound = -1; int colFound = -1; for (int row = 0; row < GameVariables.MaxRows; row++) { if (rowFound != -1) { break; } for (int col = 0; col < GameVariables.MaxCols; col++) { if (rowFound != -1) { break; } if (matrix[row, col] == null) { continue; } if (matrix[row, col].OriginalRow == rowPart && matrix[row, col].OriginalCol == colPart) { rowFound = row; colFound = col; } } } bool pieceFound = false; if (rowFound > 0 && matrix[rowFound - 1, colFound] == null) { pieceFound = true; toAnimateRow = rowFound - 1; toAnimateCol = colFound; } else if (colFound > 0 && matrix[rowFound, colFound - 1] == null) { pieceFound = true; toAnimateRow = rowFound; toAnimateCol = colFound - 1; } else if (rowFound < GameVariables.MaxRows - 1 && matrix[rowFound + 1, colFound] == null) { pieceFound = true; toAnimateRow = rowFound + 1; toAnimateCol = colFound; } else if (colFound < GameVariables.MaxCols - 1 && matrix[rowFound, colFound + 1] == null) { pieceFound = true; toAnimateRow = rowFound; toAnimateCol = colFound + 1; } if (pieceFound) { screenPosToAnimate = GetScreenCoordinatesFromViewPort(toAnimateRow, toAnimateCol); PieceToAnimate = matrix[rowFound, colFound]; gameState = GameState.Animating; } } } }
void Update() { RaycastHit2D chao = Physics2D.Raycast(chaoG.transform.position, -chaoG.transform.up, 0.1f); RaycastHit2D[] chaoall = Physics2D.RaycastAll(chaoG.transform.position, -chaoG.transform.up, 0.1f); RaycastHit2D frente = Physics2D.BoxCast(frenteG.transform.position, new Vector2(0.2f, 0.2f), 0, -frenteG.transform.up, 1f); RaycastHit2D[] frenteall = Physics2D.BoxCastAll(frenteG.transform.position, new Vector2(0.2f, 0.2f), 0, -frenteG.transform.up, 1f); RaycastHit2D ataque = Physics2D.BoxCast(frenteG.transform.position, new Vector2(0.3f, 0.2f), 0, frenteG.transform.right, 1f); RaycastHit2D[] ataqueAll = Physics2D.BoxCastAll(frenteG.transform.position, new Vector2(0.3f, 0.2f), 0, frenteG.transform.right, 1f); if (agressivo) { if (Vector2.Distance(transform.position, personagem.position) <= 1f && podeAtacar == true) { if (personagem.transform.position.x > transform.position.x) { personagem.transform.position = new Vector3(transform.position.x + 2, transform.position.y + 2, 0); } if (personagem.transform.position.x < transform.position.x) { personagem.transform.position = new Vector3(transform.position.x - 2, transform.position.y + 2, 0); } } if (ataque != false && ataque.collider.CompareTag("Player") && podeAtacar == true) { //Ataco podeAtacar = false; speed = 0; if (animal.dano > 0) { ataque.collider.GetComponent <Vida>().vidaAtual -= animal.dano; } } else if (Vector2.Distance(transform.position, personagem.position) <= 5) { speed = tmpSpeed; if (personagem.transform.position.x > transform.position.x) { angulo = 0; speed = tmpSpeed; } if (personagem.transform.position.x < transform.position.x) { angulo = 180; speed = tmpSpeed; } if (ataque && ataque.collider.CompareTag("Player")) { speed = 0; } foreach (var r in frenteall) { if (frente && r.collider.tag.StartsWith("min")) { Rigidbody2D rb = GetComponent <Rigidbody2D>(); rb.AddForce(transform.up * 20); } } transform.Translate(Vector2.right * (speed + speed) * Time.deltaTime); transform.eulerAngles = new Vector2(0, angulo); //Aumentar a velocidade //Executar um movimento. } else { agressivo = false; } GetComponent <Rigidbody2D>().isKinematic = false; GetComponent <PolygonCollider2D>().isTrigger = false; } else if (!agressivo) { if (Vector2.Distance(transform.position, personagem.position) <= 2f) { GetComponent <Rigidbody2D>().isKinematic = true; GetComponent <PolygonCollider2D>().isTrigger = true; } else { GetComponent <Rigidbody2D>().isKinematic = false; GetComponent <PolygonCollider2D>().isTrigger = false; } foreach (var c in chaoall) { if (chao && c.collider.gameObject.tag.StartsWith("min")) { foreach (var f in frenteall) { if (frente && f.collider.tag.StartsWith("min")) { if (angulo == 180) { angulo = 0; } else if (angulo == 0) { angulo = 180; } Debug.DrawLine(frente.transform.position, frente.point, Color.red); } } } } if (chao == false) { if (angulo == 180) { print("C"); angulo = 0; } else if (angulo == 0) { print("D"); angulo = 180; } } Rigidbody2D rb = GetComponent <Rigidbody2D>(); transform.Translate(Vector2.right * speed * Time.deltaTime); transform.eulerAngles = new Vector2(0, angulo); } if (speed != 0) { tmpSpeed = speed; } if (podeAtacar == false) { contador += Time.deltaTime; } if (contador >= tempoPorAtaque) { contador = 0; podeAtacar = true; } }
private void Update() { if (itemImage.sprite == null) { itemImage.color = new Color(0, 0, 0, 0); } ShowShop(); if (Input.GetMouseButtonDown(0)) //누르는 순간 { if (IsTakeOff || IsShopping || IsUseOff) //벗는게 맞거나 사는게 맞으면 { itemImage.color = new Color(255, 255, 255, 255); //selectedItem 의 그림을 움직임 pos = Camera.main.ScreenToWorldPoint(Input.mousePosition); Image_temp = Instantiate(selectedButton, selectedButton.transform); Image_temp.transform.position = pos; Image_temp.transform.SetParent(selectedButton.transform.parent.parent.parent.parent.parent); Image_temp.GetComponent <RectTransform>().sizeDelta = new Vector2(100f, 100f); } } else if (Input.GetMouseButton(0)) //누르는동안 { pos = Camera.main.ScreenToWorldPoint(Input.mousePosition); hit = Physics2D.Raycast(pos, Vector2.zero, 1000f); if (hit && (IsTakeOff || IsUseOff)) { if (hit.transform.tag == "Boundary" && inven.selectedTab == 0) //장비옮기는경우 { IsThrow = true; } else { IsThrow = false; } if (hit.transform.tag == "Boundary" && inven.selectedTab == 1) //소비옮기는경우 { IsUseThrow = true; } else { IsUseThrow = false; } if (hit.transform.tag == "Player") //장비칸으로 옮기는경우 { isMove = true; slot_num = int.Parse(hit.transform.name); } else { isMove = false; } if (hit.transform.tag == "Boss") //소비칸으로 옮기는경우 { IsUseMove = true; slot_num = int.Parse(hit.transform.name); } else { IsUseMove = false; } } else { IsThrow = false; isMove = false; IsUseThrow = false; } if (hit && IsShopping) { if (hit.transform.tag == "Boundary") //사는거면 { //탭을 옮겨줌 if (ShopList[selected_Slot + flag * shopSlots.Length].itemType == Item.ItemType.Equip) { inven.GetTabIndex(0); } else if (ShopList[selected_Slot + flag * shopSlots.Length].itemType == Item.ItemType.Use) { inven.GetTabIndex(1); } else if (ShopList[selected_Slot + flag * shopSlots.Length].itemType == Item.ItemType.ETC) { inven.GetTabIndex(2); } IsBuying = true; } else { IsBuying = false; } } else { IsBuying = false; } if (Image_temp) { Image_temp.transform.position = pos; } if (IsTakeOff) //장비아이템클릭된상태 { inven.Plus_Stat[0].text = (-equipItemList[selected_Slot]._HP).ToString(); inven.Plus_Stat[1].text = (-equipItemList[selected_Slot]._MP).ToString(); inven.Plus_Stat[2].text = (-equipItemList[selected_Slot]._PhysicalAttackPower).ToString(); inven.Plus_Stat[3].text = (-equipItemList[selected_Slot]._MagicAttackPower).ToString(); inven.Plus_Stat[4].text = (-equipItemList[selected_Slot]._PhysicalArmor).ToString(); inven.Plus_Stat[5].text = (-equipItemList[selected_Slot]._MagicArmorPower).ToString(); inven.Plus_Stat[6].text = (-equipItemList[selected_Slot]._NormalAttackRange).ToString(); inven.Plus_Stat[7].text = (-equipItemList[selected_Slot]._NormalAttackSpeed).ToString(); inven.Plus_Stat[8].text = (-equipItemList[selected_Slot].__MoveSpeed).ToString(); inven.Plus_Stat[9].text = (-equipItemList[selected_Slot]._ciritical).ToString(); inven.Plus_Stat[10].text = (-equipItemList[selected_Slot]._HP_Regenerate).ToString(); inven.Plus_Stat[11].text = (-equipItemList[selected_Slot]._MP_Regenerate).ToString(); for (int i = 0; i < 12; i++) { if (float.Parse(inven.Plus_Stat[i].text) < 0) //0보다 작으면 { inven.Plus_Stat[i].color = Color.red; } else if (float.Parse(inven.Plus_Stat[i].text) > 0) //0보다 크면 { inven.Plus_Stat[i].text = "+" + inven.Plus_Stat[i].text; inven.Plus_Stat[i].color = Color.green; } else { inven.Plus_Stat[i].color = Color.black; } } } } else if (Input.GetMouseButtonUp(0))//때면 { price.text = ""; if (Image_temp) { Destroy(Image_temp); } if (IsTakeOff) { IsTakeOff = false; selectedButton = null; if (IsThrow) { SoundManager.instance.Play(41); TakeOffItem(); } if (isMove) //교체 또는 옮기기 { //slot은 가는곳 selected_Slot 는 기존위치 SoundManager.instance.Play(38); Item temp = equipItemList[selected_Slot]; equipItemList[selected_Slot] = equipItemList[slot_num]; equipItemList[slot_num] = temp; ShowEquip(); switch (character_index) { case 0: DatabaseManager.instance.equipList0[selected_Slot] = DatabaseManager.instance.equipList0[slot_num]; DatabaseManager.instance.equipList0[slot_num] = temp; break; case 1: DatabaseManager.instance.equipList1[selected_Slot] = DatabaseManager.instance.equipList1[slot_num]; DatabaseManager.instance.equipList1[slot_num] = temp; break; case 2: DatabaseManager.instance.equipList2[selected_Slot] = DatabaseManager.instance.equipList2[slot_num]; DatabaseManager.instance.equipList2[slot_num] = temp; break; case 3: DatabaseManager.instance.equipList3[selected_Slot] = DatabaseManager.instance.equipList3[slot_num]; DatabaseManager.instance.equipList3[slot_num] = temp; break; case 4: DatabaseManager.instance.equipList4[selected_Slot] = DatabaseManager.instance.equipList4[slot_num]; DatabaseManager.instance.equipList4[slot_num] = temp; break; case 5: DatabaseManager.instance.equipList5[selected_Slot] = DatabaseManager.instance.equipList5[slot_num]; DatabaseManager.instance.equipList5[slot_num] = temp; break; case 6: DatabaseManager.instance.equipList6[selected_Slot] = DatabaseManager.instance.equipList6[slot_num]; DatabaseManager.instance.equipList6[slot_num] = temp; break; case 7: DatabaseManager.instance.equipList7[selected_Slot] = DatabaseManager.instance.equipList7[slot_num]; DatabaseManager.instance.equipList7[slot_num] = temp; break; } } } if (IsUseOff) { IsUseOff = false; selectedButton = null; if (IsUseMove) //소비창 템 옮기는거면 { SoundManager.instance.Play(38); IsUseMove = false; Item temp = useitemList[selected_Slot]; useitemList[selected_Slot] = useitemList[slot_num]; useitemList[slot_num] = temp; ShowUse(); switch (character_index) { case 0: DatabaseManager.instance.UseList0[selected_Slot] = DatabaseManager.instance.UseList0[slot_num]; DatabaseManager.instance.UseList0[slot_num] = temp; break; case 1: DatabaseManager.instance.UseList1[selected_Slot] = DatabaseManager.instance.UseList1[slot_num]; DatabaseManager.instance.UseList1[slot_num] = temp; break; case 2: DatabaseManager.instance.UseList2[selected_Slot] = DatabaseManager.instance.UseList2[slot_num]; DatabaseManager.instance.UseList2[slot_num] = temp; break; case 3: DatabaseManager.instance.UseList3[selected_Slot] = DatabaseManager.instance.UseList3[slot_num]; DatabaseManager.instance.UseList3[slot_num] = temp; break; case 4: DatabaseManager.instance.UseList4[selected_Slot] = DatabaseManager.instance.UseList4[slot_num]; DatabaseManager.instance.UseList4[slot_num] = temp; break; case 5: DatabaseManager.instance.UseList5[selected_Slot] = DatabaseManager.instance.UseList5[slot_num]; DatabaseManager.instance.UseList5[slot_num] = temp; break; case 6: DatabaseManager.instance.UseList6[selected_Slot] = DatabaseManager.instance.UseList6[slot_num]; DatabaseManager.instance.UseList6[slot_num] = temp; break; case 7: DatabaseManager.instance.UseList7[selected_Slot] = DatabaseManager.instance.UseList7[slot_num]; DatabaseManager.instance.UseList7[slot_num] = temp; break; } } if (IsUseThrow)//소비창 빼는거면 { SoundManager.instance.Play(41); IsUseThrow = false; if (useitemList[selected_Slot].itemID == 0) { return; } Useslots[selected_Slot].RemoveItem(); Item _item = new Item(0, "", "", Item.ItemType.Use); switch (character_index) { case 0: DatabaseManager.instance.UseList0[selected_Slot] = _item; break; case 1: DatabaseManager.instance.UseList1[selected_Slot] = _item; break; case 2: DatabaseManager.instance.UseList2[selected_Slot] = _item; break; case 3: DatabaseManager.instance.UseList3[selected_Slot] = _item; break; case 4: DatabaseManager.instance.UseList4[selected_Slot] = _item; break; case 5: DatabaseManager.instance.UseList5[selected_Slot] = _item; break; case 6: DatabaseManager.instance.UseList6[selected_Slot] = _item; break; case 7: DatabaseManager.instance.UseList7[selected_Slot] = _item; break; } Item temp = DatabaseManager.instance.itemList.Find(item => item.itemID == useitemList[selected_Slot].itemID); //비교해서 원래 있던 아이의 개수만 늘려주기 if (temp != null)//있으면 { temp.itemCount += useitemList[selected_Slot].itemCount; } else//없으면 { //선택한거 넣고 inven.EquipToInventory(useitemList[selected_Slot]); } //선택한거 삭제하고 useitemList[selected_Slot] = new Item(0, "", "", Item.ItemType.Use); ShowUse(); } } if (IsShopping) { selectedButton = null; IsShopping = false; if (!IsBuying) { return; } IsBuying = false; Description_Text.text = null; itemImage.sprite = Resources.Load("ItemIcon/Inven/0", typeof(Sprite)) as Sprite; item_name.text = null; price.text = null; if (ShopList[selected_Slot + flag * shopSlots.Length].money * 1f > DatabaseManager.instance.Money || DatabaseManager.instance.Money == 0) { warning_pannel.SetActive(true); warning_text.text = "금액이 부족합니다."; buy_count = 0; } else if (DatabaseManager.instance.itemList.Count == max_count) { warning_pannel.SetActive(true); warning_text.text = "아이템 소지 한도를 넘었습니다."; buy_count = 0; } else { buy_count = 1; BuyAskPannel.SetActive(true); } Buy_count_text.text = buy_count.ToString(); } } }
void SpawnNumber() { Vector3 position = Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, -Camera.main.transform.position.z)); position.z = 0; RaycastHit hit3D; Physics.Raycast(Camera.main.transform.position, Camera.main.transform.forward, out hit3D, 500); if (hit3D.collider != null) { position = hit3D.point; } else { if (Camera.main.GetComponent <DNP_DemoCamera>() != null) { return; //Only spawn numbers on ray hits. } } float number = 1 + Mathf.Pow(Random.value, 2.5f) * 200; if (numberPrefabs[currentIndex].name == "Gold") { number = 1; } if (numberPrefabs[currentIndex].name == "Big Numbers") { number *= 800000 * Random.value; } DamageNumber dn = numberPrefabs[currentIndex].CreateNew(Mathf.RoundToInt(number), position); //Creating a new Damage Number from Prefab. if (numberPrefabs[currentIndex].name == "Text") { float random = Random.value; if (random < 0.33f) { dn.prefix = "Wow"; } else if (random < 0.66f) { dn.prefix = "Nice"; } else { dn.prefix = "Great"; } } RaycastHit2D hit = Physics2D.Raycast(position, Vector2.down, 0.1f); if (hit.collider != null || hit3D.collider != null) { DNP_Player target = null; Transform targetTransform = null; if (hit.collider != null) { target = hit.collider.GetComponent <DNP_Player>(); if (target != null) { targetTransform = hit.collider.transform; } } else { if (hit3D.collider != null && hit3D.collider.GetComponent <DNP_SineMover>() != null) { targetTransform = hit3D.collider.transform; dn.followDrag = 0; dn.followSpeed = 10; } } if (targetTransform != null) { if (target != null && Input.GetMouseButtonDown(0) && numberPrefabs[currentIndex].name != "Text" && numberPrefabs[currentIndex].name != "Gold" && numberPrefabs[currentIndex].name != "Health" && numberPrefabs[currentIndex].name != "Experience") { target.Hurt(); } dn.followedTarget = targetTransform; dn.combinationSettings.combinationGroup += targetTransform.GetInstanceID(); } } if (numberPrefabs[currentIndex].name == "Outline") { dn.GetReferences(); dn.GetTextA().color = dn.GetTextB().color = Color.HSVToRGB(Random.value, 1f, 1f); } if (numberPrefabs[currentIndex].name == "Shadow") { dn.GetReferences(); dn.GetTextA().color = dn.GetTextB().color = Color.HSVToRGB(Random.value, 0.5f, 0.9f); } }
private void FixedUpdate() { m_Grounded = false; // The player is grounded if a circlecast to the groundcheck position hits anything designated as ground // This can be done using layers instead but Sample Assets will not overwrite your project settings. Collider2D[] colliders = Physics2D.OverlapCircleAll(m_GroundCheck.position, k_GroundedRadius, m_WhatIsGround); for (int i = 0; i < colliders.Length; i++) { if (colliders[i].gameObject != gameObject) { m_Grounded = true; pulseReady = true; if (colliders[i].gameObject.GetComponent <Rigidbody2D>() && !clamped) { MoveWith(colliders[i].gameObject); } } } m_Anim.SetBool("Ground", m_Grounded); // Set the vertical animation m_Anim.SetFloat("vSpeed", m_Rigidbody2D.velocity.y); // ************************************ MAG GUN ***************************************** clamped = false; if (!magPause) { RaycastHit2D hit = Physics2D.Raycast(transform.position, forward, magHeadRange, magMask); if (hit) { float distance = Mathf.Sqrt(Mathf.Pow(Mathf.Abs(transform.position.x - hit.point.x), 2) + Mathf.Pow(Mathf.Abs(transform.position.y - hit.point.y), 2)); if (distance < 1.0f && polarity > 0) { if (clampedto != hit.collider.gameObject) { GetComponent <AudioSource>().Play(); } clamped = true; clampedto = hit.collider.gameObject; } if (distance < minHeadDist) { distance = minHeadDist; } GetComponent <Rigidbody2D>().AddForce(polarity * forward * magHeadForce / distance); if (!clamped) { // if click, add lots of force in the direction. This is the pulse. if (pulseReady) { if (pulse) { if (distance < minPulseDist) { distance = minPulseDist; } GetComponent <Rigidbody2D>().AddForce(polarity * forward * pulseForce / distance); gun.GetComponent <AudioSource>().Play(); // play the pulse sound effect pulseReady = false; } } } } } // tells a bomb bot to lock on if Maggie points her magnet at it if (!magPause) { RaycastHit2D botHit = Physics2D.Raycast(transform.position, forward, magHeadRange, bombBotMask); // *** Potential problem: This could allow a bombbot to detect the magnet through a wall. if (botHit) { botHit.collider.SendMessage("LockOn"); } } // ************************************ MAG HEAD **************************************** /* * clamped = false; * if (!magPause) // if the magnet is paused, none of this stuff happens. * { * RaycastHit2D hit = Physics2D.Raycast(transform.position, Vector2.up, magHeadRange, magMask); * if (hit && !bootsActive) * { * float distance = Mathf.Abs(transform.position.y - hit.point.y); * * if (distance < 0.65f && polarity > 0) { * clamped = true; * clampedto = hit.collider.gameObject; * } * if (distance < minHeadDist) { distance = minHeadDist; } // avoid divide by zero error * GetComponent<Rigidbody2D>().AddForce(polarity * Vector2.up * magHeadForce / distance); * } * // MAG BOOTS * GetComponent<Rigidbody2D>().gravityScale = 3f; // this is needed because of how magboot repulsion works. * if (bootsActive) // MAG BOOT WHILE ATTRACTING * { * hit = Physics2D.Raycast(transform.position, Vector2.down, magBootRange, magMask); * if (hit & polarity == 1) * { * float distance = Mathf.Abs(transform.position.y - hit.point.y); * * if (distance < 0.65f && polarity > 0) { * clamped = true; * clampedto = hit.collider.gameObject; * } * if (distance < minBootDist) { distance = minBootDist; } // avoid divide by zero error * * GetComponent<Rigidbody2D>().AddForce(polarity * Vector2.down * magBootForce / ( 70 * distance)); * * // * } * else if (hit) // MAG BOOT WHILE REPELING * { * * float distance = Mathf.Abs(transform.position.y - hit.point.y); * // GetComponent<Rigidbody2D>().gravityScale = (Mathf.Pow((distance - magBootHover), 3) / (magRepDiv * distance)); * if (distance < magBootHover) { GetComponent<Rigidbody2D>().gravityScale = ((2f / (1f + Mathf.Pow(2.718f, 3f * (1 - distance)))) - 2.2f); } * if(distance >= magBootHover){ GetComponent<Rigidbody2D>().gravityScale = ((6f / (1f + Mathf.Pow(2.718f, 0.2f *(3 - distance)))) - 3f);} * * if(GetComponent<Rigidbody2D>().gravityScale < minGrav) { GetComponent<Rigidbody2D>().gravityScale = minGrav; } * if(distance > 1.172f) * { * if(distance < 2.686f) * { * GetComponent<Rigidbody2D>().velocity = new Vector2(GetComponent<Rigidbody2D>().velocity.x, (GetComponent<Rigidbody2D>().velocity.y * (Mathf.Pow((distance - 2.1f), 3f) + 0.8f))); * } * } * else * { * GetComponent<Rigidbody2D>().velocity = new Vector2(GetComponent<Rigidbody2D>().velocity.x, 0f); * } * * if(distance < 2f) * { * GetComponent<Rigidbody2D>().AddForce(magBootForce * Vector2.up); * } * * // * testDist = distance; * // * * } * }*/ // ******************************************************************************************* if (clamped) { m_Anim.SetFloat("Speed", 0f); // Maggie isn't walking if she's clamped GetComponent <Rigidbody2D>().constraints = RigidbodyConstraints2D.FreezeAll; // freeze Maggie's movement gun.GetComponent <MouseLook>().enabled = false; //MoveWith(clampedto); } else { GetComponent <Rigidbody2D>().constraints = RigidbodyConstraints2D.FreezeRotation; // unfreeze Maggie's movement gun.GetComponent <MouseLook>().enabled = true; clampedto = null; } }
public Vector2 Move(Vector2 delta, Vector2 sourcePusherLevel, int depthCount) { depthCount++; if (depthCount > 10) { return(new Vector2(0, 0)); } else { //Move attempts to move in the x dimension and then the y //it only moves us as far as we can move, and returns however far that was float direction = 0; Vector2 amountLeftToMove = delta; Vector2 totalAmountMoved = new Vector2(); List <RaycastHit2D> currentPushHits = new List <RaycastHit2D>(); List <RaycastHit2D> currentCarryHits = new List <RaycastHit2D>(); List <MovementControllerScript> hitThingsXmcs = new List <MovementControllerScript>(); List <MovementControllerScript> hitThingsYmcs = new List <MovementControllerScript>(); for (int i = 0; i < numberOfPassengerMovementPasses; i++) { Vector2 amountMoved = new Vector2(0, 0); if (Mathf.Abs(amountLeftToMove.x) > 0) { direction = Mathf.Sign(amountLeftToMove.x); currentPushHits = HorizontalRaycastHits(MIN_DISTANCE * direction); RaycastHit2D closestHit = GetClosestHit(currentPushHits); if (closestHit.transform != null) { MovementControllerScript mcs = closestHit.transform.gameObject.GetComponent <MovementControllerScript>(); if (mcs != null) { bool shouldGetPushed = (mcs.pushableLevel.x < sourcePusherLevel.x); PhysicsScript physicsScript = mcs.GetComponent <PhysicsScript>(); if (physicsScript != null) { if (physicsScript.onGround == false || physicsScript.velocity.y > 0) //this is a convulted way of checking if I'm in the air and therefore should be pushed { shouldGetPushed = true; } } if (shouldGetPushed) { hitThingsXmcs.Add(mcs); mcs.Move(new Vector2(amountLeftToMove.x, 0), sourcePusherLevel, depthCount); } } } amountMoved.x = CalculateMoveX(amountLeftToMove); List <GameObject> carryObjects = new List <GameObject>(); currentCarryHits = VerticalRaycastHits(MIN_DISTANCE); foreach (RaycastHit2D hit in currentCarryHits) { if (hit.transform != null) { if (!carryObjects.Contains(hit.transform.gameObject)) { if (hit.transform.gameObject.GetComponent <PhysicsScript>() != null) { carryObjects.Add(hit.transform.gameObject); } } } } if (carryObjects.Count > 0 && amountMoved.x != 0) { List <GameObject> carryObjectsSorted = SortGameObjectsByPositionX(carryObjects); int iStart; int iDirection; int iEnd; if (amountMoved.x < 0) { iStart = 0; iDirection = 1; iEnd = carryObjectsSorted.Count; } else { iStart = carryObjectsSorted.Count - 1; iDirection = -1; iEnd = -1; } for (int j = iStart; j != iEnd; j += iDirection) { GameObject carryObject = carryObjectsSorted[j]; MovementControllerScript mcs = carryObject.GetComponent <MovementControllerScript>(); if (mcs != null) { if (!mcs.beenCarriedThisFrame) { mcs.beenCarriedThisFrame = true; mcs.Move(new Vector2(amountMoved.x, 0)); } } } } } TranslateAndRecord(amountMoved); if (Mathf.Abs(amountLeftToMove.y) > 0) { direction = Mathf.Sign(amountLeftToMove.y); currentPushHits = VerticalRaycastHits(MIN_DISTANCE * direction); List <GameObject> hitObjects = new List <GameObject>(); foreach (RaycastHit2D hit in currentPushHits) { if (hit.transform != null) { if (!hitObjects.Contains(hit.transform.gameObject)) { hitObjects.Add(hit.transform.gameObject); } } } List <GameObject> pushedObjects = new List <GameObject>(); foreach (GameObject hitObject in hitObjects) { MovementControllerScript hitMCS = hitObject.GetComponent <MovementControllerScript>(); if (hitMCS != null) { if (hitMCS.pushableLevel.y < sourcePusherLevel.y) { if (!pushedObjects.Contains(hitMCS.gameObject)) { pushedObjects.Add(hitMCS.gameObject); } } } } float minDistanceMoved = Mathf.Infinity; float[] distancesMoved = new float[pushedObjects.Count]; for (int j = 0; j < pushedObjects.Count; j++) { GameObject pushedObject = pushedObjects[j]; MovementControllerScript hitMCS = pushedObject.GetComponent <MovementControllerScript>(); distancesMoved[j] = hitMCS.Move(new Vector2(0, amountLeftToMove.y), sourcePusherLevel, depthCount).y; if (distancesMoved[j] < minDistanceMoved) { minDistanceMoved = distancesMoved[j]; } } for (int j = 0; j < pushedObjects.Count; j++) { GameObject pushedObject = pushedObjects[j]; if (distancesMoved[j] > minDistanceMoved) { MovementControllerScript mcs = pushedObject.GetComponent <MovementControllerScript>(); if (mcs != null) { float diff = distancesMoved[j] - minDistanceMoved; mcs.Move(new Vector2(0, diff * direction * -1)); } } } List <GameObject> carryObjects = new List <GameObject>(); if (direction < 0) { currentCarryHits = VerticalRaycastHits(MIN_DISTANCE); foreach (RaycastHit2D hit in currentCarryHits) { if (hit.transform != null) { if (!carryObjects.Contains(hit.transform.gameObject)) { carryObjects.Add(hit.transform.gameObject); } } } } amountMoved.y = CalculateMoveY(amountLeftToMove); TranslateAndRecord(new Vector2(0, amountMoved.y)); if (direction < 0) { foreach (GameObject carryObject in carryObjects) { MovementControllerScript mcs = carryObject.GetComponent <MovementControllerScript>(); PhysicsScript physicsScript = carryObject.GetComponent <PhysicsScript>(); //TODO: this is not the right way to prevent things from simultaneously pulling objects down and being pushed by them if (physicsScript != null) { if (mcs.pushableLevel.y <= pusherLevel.y) { mcs.Move(new Vector2(0, amountMoved.y)); } } } } } amountLeftToMove -= amountMoved; totalAmountMoved += amountMoved; } return(totalAmountMoved); } }
// Use this for initialization private void Start() { V_Object vObject = CreateBasicUnit(transform, new Vector3(500, 680), 30f, GameAssets.i.m_MarineSpriteSheet); V_UnitAnimation unitAnimation = vObject.GetLogic <V_UnitAnimation>(); V_UnitSkeleton unitSkeleton = vObject.GetLogic <V_UnitSkeleton>(); V_IObjectTransform objectTransform = vObject.GetLogic <V_IObjectTransform>(); bool canShoot = true; V_UnitSkeleton_Composite_Weapon unitSkeletonCompositeWeapon = new V_UnitSkeleton_Composite_Weapon(vObject, unitSkeleton, GameAssets.UnitAnimEnum.dMarine_AimWeaponRight, GameAssets.UnitAnimEnum.dMarine_AimWeaponRightInvertV, GameAssets.UnitAnimEnum.dMarine_ShootWeaponRight, GameAssets.UnitAnimEnum.dMarine_ShootWeaponRightInvertV); vObject.AddRelatedObject(unitSkeletonCompositeWeapon); unitSkeletonCompositeWeapon.SetActive(); V_UnitSkeleton_Composite_Walker unitSkeletonCompositeWalker_BodyHead = new V_UnitSkeleton_Composite_Walker(vObject, unitSkeleton, GameAssets.UnitAnimTypeEnum.dMarine_Walk, GameAssets.UnitAnimTypeEnum.dMarine_Idle, new[] { "Body", "Head" }); vObject.AddRelatedObject(unitSkeletonCompositeWalker_BodyHead); V_UnitSkeleton_Composite_Walker unitSkeletonCompositeWalker_Feet = new V_UnitSkeleton_Composite_Walker(vObject, unitSkeleton, GameAssets.UnitAnimTypeEnum.dMarine_Walk, GameAssets.UnitAnimTypeEnum.dMarine_Idle, new[] { "FootL", "FootR" }); vObject.AddRelatedObject(unitSkeletonCompositeWalker_Feet); FunctionUpdater.Create(() => { Vector3 targetPosition = UtilsClass.GetMouseWorldPosition(); Vector3 aimDir = (targetPosition - vObject.GetPosition()).normalized; // Check for hits Vector3 gunEndPointPosition = vObject.GetLogic <V_UnitSkeleton>().GetBodyPartPosition("MuzzleFlash"); RaycastHit2D raycastHit = Physics2D.Raycast(gunEndPointPosition, (targetPosition - gunEndPointPosition).normalized, Vector3.Distance(gunEndPointPosition, targetPosition)); if (raycastHit.collider != null) { // Hit something targetPosition = raycastHit.point; } unitSkeletonCompositeWeapon.SetAimTarget(targetPosition); if (canShoot && Input.GetMouseButton(0)) { // Shoot canShoot = false; // Replace Body and Head with Attack unitSkeleton.ReplaceBodyPartSkeletonAnim(GameAssets.UnitAnimTypeEnum.dMarine_Attack.GetUnitAnim(aimDir), "Body", "Head"); // Shoot Composite Skeleton unitSkeletonCompositeWeapon.Shoot(targetPosition, () => { canShoot = true; }); // Add Effects Vector3 shootFlashPosition = vObject.GetLogic <V_UnitSkeleton>().GetBodyPartPosition("MuzzleFlash"); if (OnShoot != null) { OnShoot(this, new OnShootEventArgs { gunEndPointPosition = shootFlashPosition, shootPosition = targetPosition }); } //Shoot_Flash.AddFlash(shootFlashPosition); //WeaponTracer.Create(shootFlashPosition, targetPosition); } // Manual Movement bool isMoving = false; Vector3 moveDir = new Vector3(0, 0); if (Input.GetKey(KeyCode.W) || Input.GetKey(KeyCode.UpArrow)) { moveDir.y = +1; isMoving = true; } if (Input.GetKey(KeyCode.S) || Input.GetKey(KeyCode.DownArrow)) { moveDir.y = -1; isMoving = true; } if (Input.GetKey(KeyCode.A) || Input.GetKey(KeyCode.LeftArrow)) { moveDir.x = -1; isMoving = true; } if (Input.GetKey(KeyCode.D) || Input.GetKey(KeyCode.RightArrow)) { moveDir.x = +1; isMoving = true; } moveDir.Normalize(); float moveSpeed = 50f; Vector3 targetMoveToPosition = objectTransform.GetPosition() + moveDir * moveSpeed * Time.deltaTime; // Test if can move there raycastHit = Physics2D.Raycast(GetPosition() + moveDir * .1f, moveDir, Vector3.Distance(GetPosition(), targetMoveToPosition)); if (raycastHit.collider != null) { // Hit something } else { // Can move, no wall objectTransform.SetPosition(targetMoveToPosition); } if (isMoving) { Dirt_Handler.SpawnInterval(GetPosition(), moveDir * -1f); } // Update Feet unitSkeletonCompositeWalker_Feet.UpdateBodyParts(isMoving, moveDir); if (canShoot) { // Update Head and Body parts only when Not Shooting unitSkeletonCompositeWalker_BodyHead.UpdateBodyParts(isMoving, aimDir); } }); }
// Update is called once per frame void Update () { if (platformerController.collisionInfo.above || platformerController.collisionInfo.below) { velocity.y = 0; } if (shouldMove) { bounds = GetComponent<Collider2D>().bounds; //if we are currently moving right if(facingRight) { if (platformerController.collisionInfo.right == false) { //check if we will fall more than x blocks Debug.DrawRay(new Vector2(bounds.max.x, bounds.min.y), Vector2.down * 1.1f, Color.red); RaycastHit2D hit = Physics2D.Raycast(new Vector2(bounds.max.x, bounds.min.y), Vector2.down, 1.1f, ground); //hit ground if (hit.collider != null) { //Debug.Log(string.Format("Hit Object: {0}", hit.collider.gameObject)); //Debug.Log(string.Format("Hit distance: {0}", bounds.max.x, bounds.min.y)); if (hit.distance > 1) { SetDirection(false); //Debug.Log(string.Format("Flip | Speed: {0}", speed)); Flip(); } } else { SetDirection(false); //Debug.Log(string.Format("Flip | Speed: {0}", speed)); Flip(); } } else { SetDirection(false); //Debug.Log(string.Format("Flip | Speed: {0}", speed)); Flip(); } } else { if (platformerController.collisionInfo.left == false) { //check if we will fall more than x blocks Debug.DrawRay(new Vector2(bounds.min.x, bounds.min.y), Vector2.down * 1.1f, Color.red); RaycastHit2D hit = Physics2D.Raycast(new Vector2(bounds.min.x, bounds.min.y), Vector2.down, 1.1f, ground); //hit ground if (hit.collider != null) { //Debug.Log(string.Format("Hit Object: {0}", hit.collider.gameObject)); Debug.Log(string.Format("Hit distance: {0}", bounds.min.x, bounds.min.y)); if (hit.distance > 1) { SetDirection(true); Debug.Log(string.Format("Flip | Speed: {0}", speed)); Flip(); } } else { SetDirection(true); Debug.Log(string.Format("Flip | Speed: {0}", speed)); Flip(); } } else { SetDirection(true); Debug.Log(string.Format("Flip | Speed: {0}", speed)); Flip(); } } Vector2 moveInput = new Vector2(speed, 0); velocity.x = moveInput.x; } velocity.y += gravity * Time.deltaTime; platformerController.Move(velocity * Time.deltaTime); }
public static void DrawRayAndLine(LineRenderer lr, Vector3 position, float viewRange, RaycastHit2D hit, Vector3 direction) { Vector3 linePos = (viewRange * direction) + position; if (!hit) { lr.SetPosition(0, position); lr.SetPosition(1, linePos); } else { lr.SetPosition(0, position); lr.SetPosition(1, hit.point); } }
// Update is called once per frame void Update() { Vector3 mouse_pos = camera.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, 0.0f)); Vector3 touch_pos = Input.touchCount > 0 ? camera.ScreenToWorldPoint(new Vector3(Input.GetTouch(0).position.x, Input.GetTouch(0).position.y, 0.0f)) : new Vector3(-255.0f, -255.0f, 0.0f); if (Input.GetMouseButtonDown(0) || (Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Began)) { // Determine which Moon is clicked RaycastHit2D hit_mouse = Physics2D.Raycast(camera.ScreenToWorldPoint(Input.mousePosition), Vector2.zero); RaycastHit2D hit_touch = Physics2D.Raycast(camera.ScreenToWorldPoint(Input.mousePosition), Vector2.zero); if (hit_mouse.collider != null) { Debug.Log(hit_mouse.collider.gameObject.name); if (hit_mouse.collider.gameObject.GetComponent <SpriteRenderer> ().enabled) { hit_mouse.collider.gameObject.GetComponent <SpriteRenderer> ().enabled = false; } else { hit_mouse.collider.gameObject.GetComponent <SpriteRenderer> ().enabled = true; } // Forward click event to callback OnMoonSelected(hit_mouse.collider.gameObject); } else if (hit_touch.collider != null) { Debug.Log(hit_touch.collider.gameObject.name); if (hit_touch.collider.gameObject.GetComponent <SpriteRenderer> ().enabled) { hit_touch.collider.gameObject.GetComponent <SpriteRenderer> ().enabled = false; } else { hit_touch.collider.gameObject.GetComponent <SpriteRenderer> ().enabled = true; } // Forward click event to callback OnMoonSelected(hit_mouse.collider.gameObject); } // Reset button pressed if (reset_frame.Contains(new Vector2(mouse_pos.x, mouse_pos.y), true) || reset_frame.Contains(new Vector2(touch_pos.x, touch_pos.y), true)) { reset.transform.position += GlobalVariables.click_offset; } // Submit button pressed if (submit_frame.Contains(new Vector2(mouse_pos.x, mouse_pos.y), true) || submit_frame.Contains(new Vector2(touch_pos.x, touch_pos.y), true)) { submit.transform.position += GlobalVariables.click_offset; } } if (Input.GetMouseButtonUp(0) || (Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Ended)) { // Reset button released if (reset_frame.Contains(new Vector2(mouse_pos.x, mouse_pos.y), true) || reset_frame.Contains(new Vector2(touch_pos.x, touch_pos.y), true)) { reset.transform.position -= GlobalVariables.click_offset; // Forward event to callback OnReset(); } // Submit button released if (submit_frame.Contains(new Vector2(mouse_pos.x, mouse_pos.y), true) || submit_frame.Contains(new Vector2(touch_pos.x, touch_pos.y), true)) { submit.transform.position -= GlobalVariables.click_offset; // Forward event to callback OnSubmit(); } } if (Input.GetKey(KeyCode.LeftAlt) && Input.GetKey(KeyCode.F2)) { } }
/// <summary> /// we have to use a bit of trickery in this one. The rays must be cast from a small distance inside of our /// collider (skinWidth) to avoid zero distance rays which will get the wrong normal. Because of this small offset /// we have to increase the ray distance skinWidth then remember to remove skinWidth from deltaMovement before /// actually moving the player /// </summary> void moveHorizontally(ref Vector3 deltaMovement) { var isGoingRight = deltaMovement.x > 0; var rayDistance = Mathf.Abs(deltaMovement.x) + _skinWidth; var rayDirection = isGoingRight ? Vector2.right : -Vector2.right; var initialRayOrigin = isGoingRight ? _raycastOrigins.bottomRight : _raycastOrigins.bottomLeft; for (var i = 0; i < totalHorizontalRays; i++) { var ray = new Vector2(initialRayOrigin.x, initialRayOrigin.y + i * _verticalDistanceBetweenRays); DrawRay(ray, rayDirection * rayDistance, Color.red); // if we are grounded we will include oneWayPlatforms only on the first ray (the bottom one). this will allow us to // walk up sloped oneWayPlatforms if (i == 0 && collisionState.wasGroundedLastFrame) { _raycastHit = Physics2D.Raycast(ray, rayDirection, rayDistance, platformMask); } else { _raycastHit = Physics2D.Raycast(ray, rayDirection, rayDistance, platformMask & ~oneWayPlatformMask); } if (_raycastHit) { // the bottom ray can hit a slope but no other ray can so we have special handling for these cases if (i == 0 && handleHorizontalSlope(ref deltaMovement, Vector2.Angle(_raycastHit.normal, Vector2.up))) { _raycastHitsThisFrame.Add(_raycastHit); // if we weren't grounded last frame, that means we're landing on a slope horizontally. // this ensures that we stay flush to that slope if (!collisionState.wasGroundedLastFrame) { float flushDistance = Mathf.Sign(deltaMovement.x) * (_raycastHit.distance - skinWidth); transform.Translate(new Vector2(flushDistance, 0)); } break; } // set our new deltaMovement and recalculate the rayDistance taking it into account deltaMovement.x = _raycastHit.point.x - ray.x; rayDistance = Mathf.Abs(deltaMovement.x); // remember to remove the skinWidth from our deltaMovement if (isGoingRight) { deltaMovement.x -= _skinWidth; collisionState.right = true; } else { deltaMovement.x += _skinWidth; collisionState.left = true; } _raycastHitsThisFrame.Add(_raycastHit); // we add a small fudge factor for the float operations here. if our rayDistance is smaller // than the width + fudge bail out because we have a direct impact if (rayDistance < _skinWidth + kSkinWidthFloatFudgeFactor) { break; } } } }
/// <summary> /// 检测下一帧的位置是否能够移动,并进行修正 /// </summary> public void CheckNextMove() { Vector3 moveDistance = moveSpeed * Time.deltaTime; int dir = 0;//确定下一帧移动的左右方向 if (moveSpeed.x > 0) { dir = 1; } else if (moveSpeed.x < 0) { dir = -1; } else { dir = 0; } if (dir != 0)//当左右速度有值时 { RaycastHit2D lRHit2D = Physics2D.BoxCast(transform.position, boxSize, 0, Vector2.right * dir, 5.0f, playerLayerMask); if (lRHit2D.collider != null) //如果当前方向上有碰撞体 { float tempXVaule = (float)Math.Round(lRHit2D.point.x, 1); //取X轴方向的数值,并保留1位小数精度。防止由于精度产生鬼畜行为 Vector3 colliderPoint = new Vector3(tempXVaule, transform.position.y); //重新构建射线的碰撞点 float tempDistance = Vector3.Distance(colliderPoint, transform.position); //计算玩家与碰撞点的位置 if (tempDistance > (boxSize.x * 0.5f + distance)) //如果距离大于 碰撞盒子的高度的一半+最小地面距离 { transform.position += new Vector3(moveDistance.x, 0, 0); //说明此时还能进行正常移动,不需要进行修正 if (isClimb) //如果左右方向没有碰撞体了,退出爬墙状态 { isClimb = false; playAnimator.ResetTrigger("IsClimb"); //重置触发器 退出 playAnimator.SetTrigger("exitClimp"); } } else//如果距离小于 根据方向进行位移修正 { float tempX = 0;//新的X轴的位置 if (dir > 0) { tempX = tempXVaule - boxSize.x * 0.5f - distance + 0.05f; //多加上0.05f的修正距离,防止出现由于精度问题产生的鬼畜行为 } else { tempX = tempXVaule + boxSize.x * 0.5f + distance - 0.05f; } transform.position = new Vector3(tempX, transform.position.y, 0); //修改玩家的位置 if (!lRHit2D.collider.CompareTag("Trap")) //如果左右不是陷阱 { EnterClimpFunc(transform.position); //检测当前是否能够进入爬墙状态 playAnimator.ResetTrigger("exitClimp"); } else { Die(); } } } else { transform.position += new Vector3(moveDistance.x, 0, 0); if (isClimb) { isClimb = false; playAnimator.SetTrigger("exitClimp"); playAnimator.ResetTrigger("IsClimb"); //重置触发器 退出 } } } else { if (isClimb) //当左右速度无值时且处于爬墙状态时 { ExitClimpFunc(); } } //更新方向信息,上下轴 if (moveSpeed.y > 0) { dir = 1; } else if (moveSpeed.y < 0) { dir = -1; } else { dir = 0; } //上下方向进行判断 if (dir != 0) { RaycastHit2D uDHit2D = Physics2D.BoxCast(transform.position, boxSize, 0, Vector3.up * dir, 5.0f, playerLayerMask); if (uDHit2D.collider != null) { float tempYVaule = (float)Math.Round(uDHit2D.point.y, 1); Vector3 colliderPoint = new Vector3(transform.position.x, tempYVaule); float tempDistance = Vector3.Distance(transform.position, colliderPoint); if (tempDistance > (boxSize.y * 0.5f + distance)) { float tempY = 0; float nextY = transform.position.y + moveDistance.y; if (dir > 0) { tempY = tempYVaule - boxSize.y * 0.5f - distance; if (nextY > tempY) { transform.position = new Vector3(transform.position.x, tempY + 0.1f, 0); } else { transform.position += new Vector3(0, moveDistance.y, 0); } } else { tempY = tempYVaule + boxSize.y * 0.5f + distance; if (nextY < tempY) { transform.position = new Vector3(transform.position.x, tempY - 0.1f, 0); //上下方向多减少0.1f的修正距离,防止鬼畜 } else { transform.position += new Vector3(0, moveDistance.y, 0); } } isGround = false; //更新在地面的bool值 } else { float tempY = 0; if (dir > 0)//如果是朝上方向移动,且距离小于规定距离,就说明玩家头上碰到了物体,反之同理。 { tempY = uDHit2D.point.y - boxSize.y * 0.5f - distance + 0.05f; isGround = false; Debug.Log("头上碰到了物体"); } else { tempY = uDHit2D.point.y + boxSize.y * 0.5f + distance - 0.05f; Debug.Log("着地"); isGround = true; } moveSpeed.y = 0; transform.position = new Vector3(transform.position.x, tempY, 0); if (uDHit2D.collider.CompareTag("Trap")) //如果头上是陷阱 死亡 { Die(); } } } else { isGround = false; transform.position += new Vector3(0, moveDistance.y, 0); } } else { isGround = CheckIsGround();//更新在地面的bool值 } }
void Update() { //display health healthbar.GetComponent <Image>().fillAmount = health / stats.gethealth(); //Timer for damage invinsibility if (!canBeDamaged) { if (invisTimer >= invinsTime) { canBeDamaged = true; invisTimer = 0.0f; Color temp = this.GetComponent <SpriteRenderer>().color; temp.a = 1.0f; this.GetComponent <SpriteRenderer>().color = temp; transform.GetChild(0).GetComponent <SpriteRenderer>().color = temp; } invisTimer += Time.deltaTime; } //Dont do any moving if you fell in a pit if (!inPit) { //get canMove from the manager canMove = GameObject.Find("Manager").GetComponent <managerScript>().canMove; if (canMove && Input.GetMouseButton(0)) { //while not in dialouge and whilst finger is down do movement Vector3 target = Camera.main.ScreenToWorldPoint(Input.mousePosition); target.z = 0; //Stay still if you are already near the target otherwise do movement if (Vector3.Distance(transform.position, target) > stoppingRadius) { stats.rotateTowards(target); //Only move if we aren't moving into a wall. RaycastHit2D hit = Physics2D.Raycast(transform.position, this.GetComponent <reindeer>().forward, 1.0f); if (hit.collider != null) { if (hit.collider.tag == "walls") { } else { stats.moveFowards(); } } else { stats.moveFowards(); } } } //Jumping if (Input.GetKeyDown(KeyCode.Space) && canMove) { jumping = true; } if (jumping) { jumpTimer += Time.deltaTime; Vector3 temp = this.transform.position; if (jumpTimer <= 0.5f) { this.transform.position = new Vector3(temp.x, temp.y, -jumpTimer / 2.0f); } if (jumpTimer > 0.5f && jumpTimer <= jumpLength - 0.5f) { this.transform.position = new Vector3(temp.x, temp.y, -0.25f); } if (jumpTimer > jumpLength - 0.5f) { this.transform.position = new Vector3(temp.x, temp.y, -(jumpLength - jumpTimer) / 2.0f); } if (jumpTimer >= jumpLength) { this.transform.position = new Vector3(temp.x, temp.y, 0.0f); jumping = false; jumpTimer = 0.0f; } } } else { transform.localScale = Vector3.one; if (pitTimer <= 0) { SceneManager.LoadScene("Died"); } pitTimer -= Time.deltaTime; transform.localScale = Vector3.one * pitTimer / 2.0f; transform.rotation = Quaternion.Euler(0, 0, 3 * 360 * (pitTimer - 2.0f)); } }
// Update is called once per frame void Update() { //マウスのボタンの取得 // Debug.Log(_characterManeger.TargetDisplaySet()); for (int i = 0; i < 10; i++) { if (!_characterAttackCircle[i].CircleCheck()) { _characterManeger.TargetIndividualDisplay(false, _characterAttackCircle[i].GetExitCircleChara()); } } if (_manual[0].activeInHierarchy || _manual[1].activeInHierarchy || _manual[2].activeInHierarchy || _manual[3].activeInHierarchy || _manual[4].activeInHierarchy) { _characterManeger.PlayerMoveTrigger(false); _moveManual = true; } if (!_manual[0].activeInHierarchy && !_manual[1].activeInHierarchy && !_manual[2].activeInHierarchy && !_manual[3].activeInHierarchy && !_manual[4].activeInHierarchy && _turnManeger._phaseNum == 1 && _moveManual) { _characterManeger.ActionSetting(); _moveManual = false; } TargetStatusOutput(); for (int i = 0; i < 20; i++) { // Debug.Log(_characterManeger.FieldCharaDisapper(i)); if (_characterManeger.FieldCharaDisapper(i) >= 0) { _battleManeger.RingOutRun(_characterManeger.FieldCharaDisapper(i), RingOutDmage); //a = false; //b = false; } if (i >= 20) { i = -1; } } if (Input.GetMouseButtonDown(0)) { if (!_manual[0].activeInHierarchy && !_manual[1].activeInHierarchy && !_manual[2].activeInHierarchy && !_manual[3].activeInHierarchy && !_manual[4].activeInHierarchy) { //RayCastの発動 Ray ray = new Ray(); ray = Camera.main.ScreenPointToRay(Input.mousePosition); hit = Physics2D.Raycast((Vector2)ray.origin, (Vector2)ray.direction, maxDistance, layerMask); } // Debug.Log("たーん:"+_turnManeger._phaseNum); // もし、コライダーにぶつかったとき if (hit.collider) { StatusOutput(); // Debug.Log(hit.collider.gameObject.tag); if (hit.collider.gameObject.tag == "Player" || hit.collider.gameObject.tag == "SubPlayer") { _battleManeger.PlayerInput(); // Debug.Log("できたよー"); } /* if (hit.collider.gameObject.tag == "Enemy" || * hit.collider.gameObject.tag == "SubEnemy") * { * _battleManeger.EnemyInput(); * } */ PlayerBattle(); } } if (_turnManeger._phaseNum == 5) { Debug.Log("非アクティブ"); a = false; b = false; } if (_turnManeger._phaseNum == 2) { Debug.Log("非アクティブ"); a = false; b = false; } //AttackCircleChara(); //EnemyAttackCircleChara(); StatusUI_PLayer.SetActive(a); StatusUI_Enemy.SetActive(b); }
void Update() { if (!dead) { float deltaTime = Time.time - elapsedTime; Vector2 rayCast_dir = new Vector2(-(transform.position.x - player.transform.position.x), -(transform.position.y - player.transform.position.y)); RaycastHit2D playerCheck = Physics2D.Raycast(transform.position, rayCast_dir, stats.spawnRange, raycastTargets); if (playerCheck != false) { if (deltaTime > stats.spawnRate && playerCheck.transform.gameObject.layer == 9 && !nextSpawn.isSpawning) { nextSpawn.location = new Vector2(transform.position.x, transform.position.y + 2f); nextSpawn.spawn = enemy; anim.SetBool("Spawn", true); nextSpawn.isSpawning = true; } } for (int i = 0; i < spawns.Count; i++) { if (maxHealth * spawns[i].healthLeft > health && !spawns[i].spawned) { int spread = spawns[i].enemies * 2; for (int ii = 0; ii < spawns[i].enemies; ii++) { Vector2 place = new Vector2((transform.position.x + spread / 2) - spread / (ii + 1), transform.position.y + 2f); if (spawns[i].specSpawn == null) { //nextSpawn.location = place; //nextSpawn.spawn = enemy; //anim.SetBool("Spawn (test)", true); LastSpawn(Instantiate(enemy, place, transform.rotation), true); } else { //nextSpawn.location = place; //nextSpawn.spawn = spawns[i].specSpawn; //anim.SetBool("Spawn (test)", true); LastSpawn(Instantiate(spawns[i].specSpawn, place, transform.rotation), true); } } spawns[i].spawned = true; } } //Update Line if (playerCheck != false) { if (!nextSpawn.isSpawning && playerCheck.transform.gameObject.layer == 9) { bar.enabled = true; Vector3[] barPositions = { new Vector3(transform.position.x - 0.7f, transform.position.y - 1.6875f, -0.001f), new Vector3((transform.position.x - 0.7f) + (deltaTime / stats.spawnRate) * 1.4f, transform.position.y - 1.6875f, -0.001f) }; bar.SetPositions(barPositions); } else { bar.enabled = false; } } } }
void CalculatePassengerMovement(Vector3 velocity) { HashSet <Transform> movedPassengers = new HashSet <Transform>(); passengerMovement = new List <PassengerMovement>(); float directionX = Mathf.Sign(velocity.x); float directionY = Mathf.Sign(velocity.y); // Vertically moving platform if (velocity.y != 0) { float rayLength = Mathf.Abs(velocity.y) + skinWidth; for (int i = 0; i < verticalRayCount; i++) { Vector2 rayOrigin = (directionY == -1) ? raycastOrigins.bottomLeft : raycastOrigins.topLeft; rayOrigin += Vector2.right * (verticalRaySpacing * i); RaycastHit2D[] hits = Physics2D.RaycastAll(rayOrigin, Vector2.up * directionY, rayLength, passengerMask); foreach (RaycastHit2D hit in hits) { if (hit && hit.distance != 0) { if (!movedPassengers.Contains(hit.transform)) { movedPassengers.Add(hit.transform); float pushX = (directionY == 1) ? velocity.x : 0; float pushY = velocity.y - (hit.distance - skinWidth) * directionY; passengerMovement.Add(new PassengerMovement(hit.transform, new Vector3(pushX, pushY), directionY == 1, true)); } } } } } // Horizontally moving platform if (velocity.x != 0) { float rayLength = Mathf.Abs(velocity.x) + skinWidth; for (int i = 0; i < horizontalRayCount; i++) { Vector2 rayOrigin = (directionX == -1) ? raycastOrigins.bottomLeft : raycastOrigins.bottomRight; rayOrigin += Vector2.up * (horizontalRaySpacing * i); RaycastHit2D hit = Physics2D.Raycast(rayOrigin, Vector2.right * directionX, rayLength, passengerMask); if (hit && hit.distance != 0) { if (!movedPassengers.Contains(hit.transform)) { movedPassengers.Add(hit.transform); float pushX = velocity.x - (hit.distance - skinWidth) * directionX; float pushY = -skinWidth; passengerMovement.Add(new PassengerMovement(hit.transform, new Vector3(pushX, pushY), false, true)); } } } } // Passenger on top of a horizontally or downward moving platform if (directionY == -1 || velocity.y == 0 && velocity.x != 0) { float rayLength = skinWidth * 2; for (int i = 0; i < verticalRayCount; i++) { Vector2 rayOrigin = raycastOrigins.topLeft + Vector2.right * (verticalRaySpacing * i); RaycastHit2D hit = Physics2D.Raycast(rayOrigin, Vector2.up, rayLength, passengerMask); if (hit && hit.distance != 0) { if (!movedPassengers.Contains(hit.transform)) { movedPassengers.Add(hit.transform); float pushX = velocity.x; float pushY = velocity.y; passengerMovement.Add(new PassengerMovement(hit.transform, new Vector3(pushX, pushY), true, false)); } } } } }
// Update is called once per frame void Update() { #region Laser Attack if (laserCounter < laserTime) { laserCounter += Time.deltaTime; } else if (GetComponent <LineRenderer>().GetPosition(0) != Vector3.zero) { GetComponent <LineRenderer>().SetPosition(0, Vector3.zero); GetComponent <LineRenderer>().SetPosition(1, Vector3.zero); } // On cooldown for laser attack if (cooldownLaserCounter < cooldownLaser) { cooldownLaserCounter += Time.deltaTime; float hue; float sat; float val; Color.RGBToHSV(headSprite.color, out hue, out sat, out val); val = 0.5f + (cooldownLaserCounter / cooldownLaser * 0.5f); headSprite.color = Color.HSVToRGB(hue, sat, val); //Color currentCol = GetComponent<LineRenderer>().material.color; //GetComponent<LineRenderer>().material.color = new Color(currentCol.r, currentCol.g, currentCol.b, 1 - (cooldownLaserCounter / cooldownLaser)); } // Can attack again else if (cooldownLaserCounter >= cooldownLaser) { // Remove beam if (GetComponent <LineRenderer>().GetPosition(0) != Vector3.zero) { GetComponent <LineRenderer>().SetPosition(0, Vector3.zero); GetComponent <LineRenderer>().SetPosition(1, Vector3.zero); } if (Input.GetButtonDown("Fire1") && stats.head != null) { // To Do: Charge attack } else if (Input.GetButtonUp("Fire1") && stats.head != null) { Vector3 worldMouse = Camera.main.ScreenToWorldPoint(Input.mousePosition); Vector3 dir = (worldMouse - stats.headPos.position).normalized; List <Collider2D> collidersHit = new List <Collider2D>(); RaycastHit2D hit = Physics2D.Raycast(stats.headPos.position, dir); GetComponent <LineRenderer>().SetPosition(0, new Vector3(stats.headPos.position.x, stats.headPos.position.y)); Color currentCol = GetComponent <LineRenderer>().material.color; GetComponent <LineRenderer>().material.color = new Color(currentCol.r, currentCol.g, currentCol.b, 1); laserCounter = 0; if (hit.collider != null) { collidersHit.Add(hit.collider); // Extend the raycast while (hit.collider.tag != "Ground") { hit = Physics2D.Raycast(hit.point + new Vector2(dir.x, dir.y), dir); if (hit.collider != null) { collidersHit.Add(hit.collider); } else // Didn't hit anything { break; } } GetComponent <LineRenderer>().SetPosition(1, hit.point); // Damage all enemies and destroy breakable blocks foreach (Collider2D collider in collidersHit) { if (collider.tag == "Enemy") { collider.GetComponent <EnemyStats>().TakeDamage(stats.damage); } else if (collider.tag == "Breakable") { Destroy(collider.gameObject); } } } controller.laserSound.Play(); // Set on cooldown cooldownLaserCounter = 0; headSprite = stats.GetComponent <SpriteRenderer>(); } } #endregion // On cooldown for normal attack if (cooldownGunCounter < cooldownGun) { cooldownGunCounter += Time.deltaTime; } // Can attack again else if (cooldownGunCounter >= cooldownGun) { if (Input.GetButton("Fire2") && (stats.leftArm != null || stats.rightArm != null)) { if (stats.leftArm != null) { controller.shootSound.Play(); GameObject bullet = Instantiate(projectile, stats.leftArm.transform.position, projectile.transform.rotation); bullet.GetComponentInChildren <PlayerProjectile>().moveLeft = GetComponent <SpriteRenderer>().flipX; bullet.GetComponentInChildren <SpriteRenderer>().flipY = !GetComponent <SpriteRenderer>().flipX; } if (stats.rightArm != null) { controller.shootSound.Play(); GameObject bullet = Instantiate(projectile, stats.rightArm.transform.position, projectile.transform.rotation); bullet.GetComponentInChildren <PlayerProjectile>().moveLeft = GetComponent <SpriteRenderer>().flipX; bullet.GetComponentInChildren <SpriteRenderer>().flipY = !GetComponent <SpriteRenderer>().flipX; } // Set on cooldown cooldownGunCounter = 0; } } }
void Update () { //int x = 1; for (int i = 0; i < Input.touchCount; i++) { Touch touch = Input.GetTouch (i); if (touch.phase == TouchPhase.Ended) { Ray ray = Camera.main.ScreenPointToRay (touch.position); RaycastHit2D hit = Physics2D.Raycast (ray.origin, ray.direction); if (hit.collider != null) { // D if (hit.collider.tag == "Player") { #region Hit Player // Destroy (GameObject.Find ("FadePlayer" + x.ToString ())); WallScript wallsc = hit.transform.GetComponent<WallScript> (); if (wallsc) { selectedwall = hit.transform.gameObject; selected=wallsc.id; fadeeverything (); m1 = wallsc.PossibleLeftMove (); m2 = wallsc.PossibleRightMove (); fadeit = GameObject.Find ("FadePlayer" + m1.ToString ()); FaderScript fadescript = fadeit.GetComponent<FaderScript> (); WallScript tofade = fadeit.GetComponent<WallScript> (); if(wallsc.owner==0) { if (tofade.owner == wallsc.id || tofade.owner == 0) fadescript.fading = true; fadeit = GameObject.Find ("FadePlayer" + m2.ToString ()); tofade = fadeit.GetComponent<WallScript> (); fadescript = fadeit.GetComponent<FaderScript> (); if (tofade.owner == wallsc.id || tofade.owner == 0) fadescript.fading = true; } else { if (tofade.owner == wallsc.id) fadescript.fading = true; fadeit = GameObject.Find ("FadePlayer" + m2.ToString ()); tofade = fadeit.GetComponent<WallScript> (); fadescript = fadeit.GetComponent<FaderScript> (); if (tofade.owner == wallsc.id) fadescript.fading = true; } } } #endregion #region Hit RedWall else if (hit.collider.tag == "Redwall"&&selectedwall!=null) { WallScript ownerid = selectedwall.GetComponent<WallScript> (); WallScript getid = hit.collider.gameObject.GetComponent<WallScript> (); if (ownerid.owner == 0) { if (getid.owner == 0) { if (getid.id == m1 || getid.id == m2) { getid.owner = selected; ownerid.owner = 1; Vector3 savepos = selectedwall.transform.position; selectedwall.transform.position = hit.collider.transform.position; hit.collider.transform.position = savepos; } else { selected = 0; // m1 = 0; // m2 = 0; fadeeverything (); } } else if (getid.owner == selected) { getid.owner = 0; if (getid.id == m1 || getid.id == m2) { ownerid.owner = 1; Vector3 savepos = selectedwall.transform.position; selectedwall.transform.position = hit.collider.transform.position; hit.collider.transform.position = savepos; } else { //selected = 0; // m1 = 0; // m2 = 0; fadeeverything (); } } } else { if (getid.owner == selected) { getid.owner = 0; if (getid.id == m1 || getid.id == m2) { ownerid.owner = 0; Vector3 savepos = selectedwall.transform.position; selectedwall.transform.position = hit.collider.transform.position; hit.collider.transform.position = savepos; } } } } #endregion } else { // selectedwall=null; fadeeverything(); } } else { if (touch.phase == TouchPhase.Began) { Debug.Log("I'm Here"); Ray ray = Camera.main.ScreenPointToRay (touch.position); RaycastHit2D hit = Physics2D.Raycast (ray.origin, ray.direction); if (hit.collider != null) { // D if (hit.collider.tag == "Player") { // Destroy (GameObject.Find ("FadePlayer" + x.ToString ())); WallScript wallsc = hit.transform.GetComponent<WallScript> (); if (wallsc) { selectedwall = hit.transform.gameObject; selected=wallsc.id; fadeeverything (); m1 = wallsc.PossibleLeftMove (); m2 = wallsc.PossibleRightMove (); fadeit = GameObject.Find ("FadePlayer" + m1.ToString ()); FaderScript fadescript = fadeit.GetComponent<FaderScript> (); WallScript tofade = fadeit.GetComponent<WallScript> (); if(wallsc.owner==0) { if (tofade.owner == wallsc.id || tofade.owner == 0) fadescript.fading = true; fadeit = GameObject.Find ("FadePlayer" + m2.ToString ()); tofade = fadeit.GetComponent<WallScript> (); fadescript = fadeit.GetComponent<FaderScript> (); if (tofade.owner == wallsc.id || tofade.owner == 0) fadescript.fading = true; } else { if (tofade.owner == wallsc.id) fadescript.fading = true; fadeit = GameObject.Find ("FadePlayer" + m2.ToString ()); tofade = fadeit.GetComponent<WallScript> (); fadescript = fadeit.GetComponent<FaderScript> (); if (tofade.owner == wallsc.id) fadescript.fading = true; } } } } } else if (touch.phase == TouchPhase.Moved) { // Move the trail Ray ray = Camera.main.ScreenPointToRay (touch.position); RaycastHit2D hit = Physics2D.Raycast (ray.origin, ray.direction); if (hit.collider != null) { // D if (hit.collider.tag == "Redwall"&&selectedwall!=null) { WallScript ownerid = selectedwall.GetComponent<WallScript> (); WallScript getid = hit.collider.gameObject.GetComponent<WallScript> (); if (ownerid.owner == 0) { if (getid.owner == 0) { if (getid.id == m1 || getid.id == m2) { getid.owner = selected; ownerid.owner = 1; Vector3 savepos = selectedwall.transform.position; selectedwall.transform.position = hit.collider.transform.position; hit.collider.transform.position = savepos; } else { selected = 0; //m1 = 0; //m2 = 0; fadeeverything (); } } else if (getid.owner == selected) { getid.owner = 0; if (getid.id == m1 || getid.id == m2) { ownerid.owner = 1; Vector3 savepos = selectedwall.transform.position; selectedwall.transform.position = hit.collider.transform.position; hit.collider.transform.position = savepos; } else { //selected = 0; // m1 = 0; // m2 = 0; fadeeverything (); } } } else { if (getid.owner == selected) { getid.owner = 0; if (getid.id == m1 || getid.id == m2) { ownerid.owner = 0; Vector3 savepos = selectedwall.transform.position; selectedwall.transform.position = hit.collider.transform.position; hit.collider.transform.position = savepos; } } } } } } else if (touch.phase == TouchPhase.Ended) { // Clear known trails } } } }
IEnumerator LaserAttack() { rb.gravityScale = 0f; while (!(transform.position.y + .5f > player.transform.position.y && transform.position.y - 1f < player.transform.position.y)) { float step = verticalSpeed * Time.fixedDeltaTime; Vector3 targetPosition = new Vector3(transform.position.x, player.transform.position.y, 0f); if (transform.position.y < -5f) { targetPosition.y = Mathf.Clamp(targetPosition.y, -33f, -26.75f); } else { targetPosition.y = Mathf.Clamp(targetPosition.y, -4f, 2.25f); } transform.position = Vector3.MoveTowards(transform.position, targetPosition, step); if ((targetPosition.x > player.transform.position.x && control.facingRight) || (targetPosition.x < player.transform.position.x && !control.facingRight)) { control.Flip(); } yield return(null); } RaycastHit2D hit = Physics2D.Raycast(globalShootPosition, control.facingRight ? Vector2.right : -Vector2.right, Mathf.Infinity, laserCollisionMask); if (hit) { chargeLight.gameObject.SetActive(true); float intensity = chargeLight.intensity; for (int i = 0; i < framesBeforeLaser; i++) { float percentage = (float)i * (1f / framesBeforeLaser); chargeLight.intensity = Mathf.Lerp(0f, intensity, percentage); yield return(null); } laserQueue = new Queue <Projectiles.Projectile>(); for (float dx = 0f; dx < hit.distance; dx += (float)1f / 8f) { Projectiles.Projectile laserCopy = laserPool.Dequeue(); laserCopy.instance.SetActive(true); laserQueue.Enqueue(laserCopy); int directionX = control.facingRight ? 1 : -1; laserCopy.instance.transform.position = transform.position + new Vector3(dx * directionX, 0f, 0f); } for (int i = 0; i < laserDurationFrames; i++) { yield return(null); } RecallLasers(); } OnAttackComplete(); }
// Update is called once per frame void Update() { // Horizontal movement A:-1, D: 1 0 float moveX = Input.GetAxisRaw("Horizontal"); // Vertical movement W: 1 S:-1 0 float moveY = Input.GetAxisRaw("Vertical"); Vector2 moveVector = new Vector2(moveX, moveY); if (moveVector.x != 0 || moveVector.y != 0) { lookDirection = moveVector; } anim.SetFloat("Look X", lookDirection.x); anim.SetFloat("Look Y", lookDirection.y); anim.SetFloat("Speed", moveVector.magnitude); // ================ movement ================ Vector2 position = rbody.position; position += moveVector * speed * Time.deltaTime; rbody.MovePosition(position); // ================= INVICIBLE TIMER if (isInvincible) { invincibleTimer -= Time.deltaTime; if (invincibleTimer < 0) { isInvincible = false; } } // ======= press 'J' for attack enemies ================== if (Input.GetKeyDown(KeyCode.J) && curBulletCount > 0) { ChangeBulletCount(-1); anim.SetTrigger("Launch"); audioManager.instance.AudioPlay(launchClip); // lauch sound GameObject bullet = Instantiate(bulletPrefab, rbody.position + Vector2.up * 0.5f, Quaternion.identity); bulletController bc = bullet.GetComponent <bulletController>(); if (bc != null) { bc.Move(lookDirection, 300); } } // ============ press 'K' for npc interaction =============== if (Input.GetKeyDown(KeyCode.K)) { RaycastHit2D hit = Physics2D.Raycast(rbody.position, lookDirection, 2f, LayerMask.GetMask("npc")); if (hit.collider != null) { NPCManager npc = hit.collider.GetComponent <NPCManager>(); if (npc != null) { npc.ShowDialog(); } } } }
void OnTriggerStay2D(Collider2D other) { if (other.gameObject != player) { return; } if (investigateCol.IsTouching(other)) { playerInSight = false; Vector2 dir = other.transform.position - enemyViewStart.position; float angle = Vector2.Angle(dir, enemyFacing); if (angle < fieldOfViewAngle * 0.5) { RaycastHit2D hit = Physics2D.Raycast(enemyViewStart.position, dir.normalized, investigateCol.radius); Debug.DrawRay(enemyViewStart.position, dir, Color.yellow, 0.1f); if (hit.collider == null) { return; } if ((hit.collider.gameObject == player) && (playerMovement.isSneaking == false)) { personalLastSighting = player.transform.position; } } } if (viewCol.IsTouching(other)) { playerInSight = false; Vector2 dir = other.transform.position - enemyViewStart.position; float angle = Vector2.Angle(dir, enemyFacing); if (angle < (fieldOfViewAngle / 2)) { RaycastHit2D hit = Physics2D.Raycast(enemyViewStart.position, dir.normalized, viewCol.radius); Debug.DrawRay(enemyViewStart.position, dir, Color.blue, 0.1f); if (hit.collider.gameObject == player) { Debug.DrawRay(enemyViewStart.position, dir, Color.red, 0.1f); playerInSight = true; personalLastSighting = player.transform.position; } } } if (hearCol.IsTouching(other)) { if ((playerMovement.isSneaking == false) && (playerMovement.moveX > 0)) { personalLastSighting = player.transform.position; } else if (ai.enemyState == EnemyAI.EnemyState.chase) { personalLastSighting = player.transform.position; playerInSight = true; } } }
public void Shoot() { //play gunshot sound (multiple sources are cycled through so they can overlap) gunfireAudioSources[gunfireAudioSourceIndex].pitch = UnityEngine.Random.Range(.8f, 1.2f); gunfireAudioSources[gunfireAudioSourceIndex].Play(); gunfireAudioSourceIndex++; if (gunfireAudioSourceIndex >= gunfireAudioSources.Length) { gunfireAudioSourceIndex = 0; } for (int i = 0; i < bulletsPerShot; i++) { //select a bullet trail line. multiple can be used so they are on screen at the same time. LineRenderer currentBulletTrailLine = bulletTrailLines[bulletTrailIndex]; bulletTrailIndex++; if (bulletTrailIndex >= bulletTrailLines.Length) { bulletTrailIndex = 0; } //generate the angle and distance this bullet will shoot int trueAngle = UtilsClass.GetAngleFromVector(firePoint.up); Vector2 noisyAngle = UtilsClass.GetVectorFromAngle(trueAngle + (int)Random.Range(-angleVariability / 2, angleVariability / 2)); float noisyRange = range + UnityEngine.Random.Range(-rangeVariability / 2, rangeVariability / 2); //fire the raycast RaycastHit2D hitInfo = Physics2D.Raycast(firePoint.position, noisyAngle, noisyRange, bulletHitMask); if (hitInfo) { currentBulletTrailLine.SetPosition(0, firePoint.position); currentBulletTrailLine.SetPosition(1, hitInfo.point); if (hitInfo.collider.gameObject.layer == LayerMask.NameToLayer("Walls") || hitInfo.collider.gameObject.layer == LayerMask.NameToLayer("Obsticles")) { try { Vector3 hitPosition = Vector3.zero; hitPosition.x = hitInfo.point.x + noisyAngle.normalized.x * .01f; hitPosition.y = hitInfo.point.y + noisyAngle.normalized.y * .01f;; hitInfo.collider.gameObject.GetComponent <DestructableTilemap>().ShootBlock(hitPosition, bulletDamage); } catch { } } if (hitInfo.collider.gameObject.layer == LayerMask.NameToLayer("Player")) { hitInfo.collider.gameObject.GetComponent <Rigidbody2D>().AddForce(noisyAngle.normalized * bulletKnockBack); hitInfo.collider.gameObject.GetComponent <PlayerBase>().ChangeHealth(-bulletDamage); } if (hitInfo.collider.gameObject.layer == LayerMask.NameToLayer("Hostile")) { hitInfo.collider.gameObject.GetComponent <Rigidbody2D>().AddForce(noisyAngle.normalized * bulletKnockBack); hitInfo.collider.gameObject.GetComponent <EnemyBehavior2>().Damage(bulletDamage, this.transform.parent.gameObject); } } else //draw bullet trail for missed bullet { Vector3 missPoistionFromBarrel = noisyRange * noisyAngle.normalized; currentBulletTrailLine.SetPosition(0, firePoint.position); currentBulletTrailLine.SetPosition(1, firePoint.position + missPoistionFromBarrel); } StartCoroutine(HideBulletTrail(currentBulletTrailLine)); } }
// Update is called once per frame void Update() { Vector3 targetPosition = camera.ScreenToWorldPoint(Input.mousePosition); SetAimDirection(targetPosition); Vector3 origin = Vector3.zero; float angle = startingAngle; float angleIncrease = fov / rayCount; Vector3[] vertices = new Vector3[rayCount + 1 + 1]; Vector2[] uv = new Vector2[vertices.Length]; int[] triangles = new int[rayCount * 3]; vertices[0] = origin; int vertexIndex = 1; int triangleIndex = 0; for (int i = 0; i <= rayCount; i++) { Vector3 vertex; RaycastHit2D raycastHit2D = Physics2D.Raycast(origin, GetVectorFromAngle(angle), viewDistance, layerMask); if (raycastHit2D.collider == null) { // No Hit vertex = origin + GetVectorFromAngle(angle) * viewDistance; } else { // Hit Object vertex = raycastHit2D.point; } vertices[vertexIndex] = vertex; if (i > 0) { triangles[triangleIndex + 0] = 0; triangles[triangleIndex + 1] = vertexIndex - 1; triangles[triangleIndex + 2] = vertexIndex; triangleIndex += 3; } vertexIndex++; // Adding makes the angle go counterclockwise rather than clockwise angle -= angleIncrease; } triangles[0] = 0; triangles[1] = 1; triangles[2] = 2; mesh.vertices = vertices; mesh.uv = uv; mesh.triangles = triangles; }
protected override bool PerformRaycast(GvrBasePointer.PointerRay pointerRay, float radius, PointerEventData eventData, List <RaycastResult> resultAppendList) { if (canvas == null) { return(false); } if (eventCamera == null) { return(false); } if (canvas.renderMode != RenderMode.WorldSpace) { Debug.LogError("GvrPointerGraphicRaycaster requires that the canvas renderMode is set to WorldSpace."); return(false); } float hitDistance = float.MaxValue; if (blockingObjects != BlockingObjects.None) { float dist = pointerRay.distance; if (blockingObjects == BlockingObjects.ThreeD || blockingObjects == BlockingObjects.All) { RaycastHit hit; if (Physics.Raycast(pointerRay.ray, out hit, dist, blockingMask)) { hitDistance = hit.distance; } } if (blockingObjects == BlockingObjects.TwoD || blockingObjects == BlockingObjects.All) { RaycastHit2D hit = Physics2D.Raycast(pointerRay.ray.origin, pointerRay.ray.direction, dist, blockingMask); if (hit.collider != null) { hitDistance = hit.fraction * dist; } } } raycastResults.Clear(); Ray finalRay; Raycast(canvas, pointerRay.ray, eventCamera, pointerRay.distance, raycastResults, out finalRay); bool foundHit = false; for (int index = 0; index < raycastResults.Count; index++) { GameObject go = raycastResults[index].gameObject; bool appendGraphic = true; if (ignoreReversedGraphics) { // If we have a camera compare the direction against the cameras forward. Vector3 cameraFoward = eventCamera.transform.rotation * Vector3.forward; Vector3 dir = go.transform.rotation * Vector3.forward; appendGraphic = Vector3.Dot(cameraFoward, dir) > 0; } if (appendGraphic) { float resultDistance = 0; Transform trans = go.transform; Vector3 transForward = trans.forward; // http://geomalgorithms.com/a06-_intersect-2.html float transDot = Vector3.Dot(transForward, trans.position - pointerRay.ray.origin); float rayDot = Vector3.Dot(transForward, pointerRay.ray.direction); resultDistance = transDot / rayDot; Vector3 hitPosition = pointerRay.ray.origin + (pointerRay.ray.direction * resultDistance); resultDistance = resultDistance + pointerRay.distanceFromStart; // Check to see if the go is behind the camera. if (resultDistance < 0 || resultDistance >= hitDistance || resultDistance > pointerRay.distance) { continue; } Transform pointerTransform = GvrPointerInputModule.Pointer.PointerTransform; float delta = (hitPosition - pointerTransform.position).magnitude; if (delta < pointerRay.distanceFromStart) { continue; } RaycastResult castResult = new RaycastResult { gameObject = go, module = this, distance = resultDistance, worldPosition = hitPosition, screenPosition = eventCamera.WorldToScreenPoint(hitPosition), index = resultAppendList.Count, depth = raycastResults[index].depth, sortingLayer = canvas.sortingLayerID, sortingOrder = canvas.sortingOrder }; resultAppendList.Add(castResult); foundHit = true; } } return(foundHit); }
void Update() { // Put rope control here! if (Input.GetKeyDown("q")) { Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition); if (hit = Physics2D.Raycast(transform.position, Camera.main.ScreenToWorldPoint(Input.mousePosition),75,(1<<0))){ Debug.DrawLine(ray.origin, hit.point, Color.red, 3); StartPos = new Vector2(transform.position.x, transform.position.y); EndPos = hit.point; target = hit.transform; Debug.Log (EndPos); //MoveTo = true; // Enables the lerp function to update until it's finished, or cancelled. if(!rope) { Debug.Log(StartPos); BuildRope(); moveOk = true; } } } if (moveOk && rope && Input.GetKeyDown ("v")) { body.gravityScale = 0; float step = speed * Time.deltaTime; transform.position = Vector2.MoveTowards(transform.position, EndPos, step); if (new Vector2(transform.position.x,transform.position.y) == EndPos){ // This enables gravity when you're done moving. If you're using a rigidbody you could use rigidbody.isKinematic = true; to turn gravity back on. moveOk = false; } } if (Input.GetKeyUp ("v") && (body.gravityScale == 0)) { body.gravityScale = 1; } //Destroy Rope Test (Example of how you can use the rope dynamically) if(rope && Input.GetKeyDown("b")) { DestroyRope(); } }
void Update() { float coolDown = Random.Range(minCoolDown, coolDownMax); currentTime = Time.time; if (currentTime - startTime > coolDown) { if (isActive) { isActive = false; isTiming = false; } else { isActive = true; isTiming = false; } } if (isActive) { for (int i = 0; i < this.transform.childCount; i++) { this.transform.GetChild(i).gameObject.SetActive(true); } if (!isTiming) { isTiming = true; startTime = currentTime; } } else { for (int i = 0; i < this.transform.childCount; i++) { this.transform.GetChild(i).gameObject.SetActive(false); } if (!isTiming) { isTiming = true; startTime = currentTime; } } RaycastHit2D roombahit = Physics2D.Raycast(transform.position, transform.up, 0.4f); //shoots raycast if (roombahit.collider != null && roombahit.collider.gameObject.tag != "Zombie") //if raycast hits something { float randomNumber = Random.Range(0f, 1f); //turn randomly 90 degreees left or right if (randomNumber > 0.5f) { transform.Rotate(0f, 0f, 90f); } else { transform.Rotate(0f, 0f, -90f); } } else //if raycast hits nothing, always go forward { transform.position += transform.up * Time.deltaTime; } }