void MobileControl() { if (Input.touches.Length > 0) { Touch t = Input.GetTouch(0); if (t.phase == TouchPhase.Began) { firstPressPos = new Vector2(t.position.x, t.position.y); } if (t.phase == TouchPhase.Ended) { secondPressPos = new Vector2(t.position.x, t.position.y); currentSwipe = new Vector3(secondPressPos.x - firstPressPos.x, secondPressPos.y - firstPressPos.y); currentSwipe.Normalize(); //strafe left if (currentSwipe.x < 0 && movRange > -1) { transform.position += new Vector3(-1, 0, 0); movRange--; } //strafe right if (currentSwipe.x > 0 && movRange < 1) { transform.position += new Vector3(1, 0, 0); movRange++; } } } }
// public override void OnCollisionEnter2D (Collision2D collision) // { // base.OnCollisionEnter2D (collision); // // Make the bullet smaller before multiplying // this.transform.localScale *= scaleFactor; // // If this object is bigger than the min size for a bullet // if (this.gameObject.transform.localScale.x > minSize) { // // Split into <splitAmount> pieces that go in different directions // float degreeChange = 360.0f/splitAmount; // for (float i = 0; i < 360; i+= degreeChange) // { // float x = Mathf.Cos(i); // float y = Mathf.Sin(i); // // // Make a copy of this splitter // GameObject splitBullet = (GameObject)Instantiate(this.gameObject, this.transform.position, Quaternion.identity); // // // Make it go towards the direction we want // Vector2 vel = new Vector2(x,y); // // Make sure that bullet goes in the speed we want // vel.Normalize(); // vel *= base.projectileSpeed; // // Make the split bullets actual velocity the correct one // splitBullet.GetComponent<Rigidbody2D>().velocity = vel; // } // } // } public override void OnTriggerEnter2D(Collider2D collider) { base.OnTriggerEnter2D (collider); // Make the bullet smaller before multiplying this.transform.localScale *= scaleFactor; // If this object is bigger than the min size for a bullet if (this.gameObject.transform.localScale.x > minSize) { // Split into <splitAmount> pieces that go in different directions float degreeChange = 360.0f/splitAmount; for (float i = 0; i < 360; i+= degreeChange) { float x = Mathf.Cos(i); float y = Mathf.Sin(i); // Make a copy of this splitter GameObject splitBullet = (GameObject)Instantiate(this.gameObject, this.transform.position, Quaternion.identity); // Make it go towards the direction we want Vector2 vel = new Vector2(x,y); // Make sure that bullet goes in the speed we want vel.Normalize(); vel *= base.projectileSpeed; // Make the split bullets actual velocity the correct one splitBullet.GetComponent<Rigidbody2D>().velocity = vel; } } }
// Use this for initialization void Start() { rigidBody2D = GetComponent<Rigidbody2D>(); dir = transform.rotation * Vector2.up; dir.Normalize(); rigidBody2D.AddForce(dir * initialForce); }
// Update is called once per frame void Update() { float moveX = Input.GetAxis ("Horizontal"); moveDir = new Vector2 (moveX, 0); moveDir.Normalize (); anim.SetFloat ("Speed", Math.Abs(moveX)); //horizontal move control transform.position += new Vector3 (moveDir.x, moveDir.y, 0.0f)*moveSpeed*Time.deltaTime; if (moveX > 0) { transform.localScale = new Vector3(Math.Abs(transform.localScale.x), transform.localScale.y, transform.localScale.z); } else if (moveX < 0) { transform.localScale = new Vector3(-Math.Abs(transform.localScale.x), transform.localScale.y, transform.localScale.z); } //jump control if (rb.velocity.y >= -0.01f && rb.velocity.y <= 0.01f && Input.GetKeyDown (KeyCode.Space)) { rb.AddForce(new Vector2(0, jumpForce)); } anim.SetFloat ("vSpeed", rb.velocity.y); }
void FixedUpdate() { direc = new Vector2(Input.GetAxis("Horizontal"),Input.GetAxis("Vertical")); direc.Normalize(); rbody.AddForce(rbody.mass * direc * brain.currentSpeed); }
/* void addV(Vector2 v) { VelAdd += v; if(VelAdd.sqrMagnitude > MaxFrc * MaxFrc) { VelAdd = VelAdd.normalized * MaxFrc; } }*/ void Update() { // if( (Timer -= Time.deltaTime ) > 0 ) return; if((Timer -= Time.deltaTime) < 0) { Timer = Freq; var lyr = gameObject.layer; gameObject.layer = 31; VelAdd = Vector2.zero; var cols = Physics2D.OverlapCircleAll(Motor.Trnsfrm.position, Radius, Layers); foreach(var c in cols) { var rep = c.gameObject.GetComponent<Repulsor>(); if(rep == null) continue; Vector2 add = (Motor.Trnsfrm.position - rep.Motor.Trnsfrm.position).normalized;// *Frc; // rep.addV(-add); // addV(add); VelAdd += add; // Debug.Log("rep?"); } VelAdd.Normalize(); gameObject.layer = lyr; } if(VelAdd == Vector2.zero ) return; //no ep required Motor.DesVec.Normalize(); var dot = Vector2.Dot(Motor.DesVec, VelAdd ); if(dot < -0.7f) { Motor.DesVec = (Motor.DesVec + Vector2.Lerp(VelAdd, (Vector2)Vector3.Cross(Vector3.back, VelAdd), (dot + 0.7f) * 4.0f) ).normalized; } else Motor.DesVec = (Motor.DesVec + VelAdd).normalized; }
protected override void TickCore(Entity host, RealmTime time, ref object state) { int cooldown; if (state == null) cooldown = 1000; else cooldown = (int)state; Status = CycleStatus.NotStarted; if (host.HasConditionEffect(ConditionEffectIndex.Paralyzed)) return; Player player = (Player)host.GetNearestEntity(distance, null); if (player != null) { Vector2 vect; vect = new Vector2(player.X - host.X, player.Y - host.Y); vect.Normalize(); float dist = host.GetSpeed(speed) * (time.thisTickTimes / 1000f); host.ValidateAndMove(host.X + (-vect.X) * dist, host.Y + (-vect.Y) * dist); host.UpdateCount++; if (cooldown <= 0) { Status = CycleStatus.Completed; cooldown = 1000; } else { Status = CycleStatus.InProgress; cooldown -= time.thisTickTimes; } } state = cooldown; }
// Update is called once per frame public override void ControlledUpdateOwner(PlayerController controller) { float xMove = Input.GetAxisRaw("Horizontal"); float yMove = Input.GetAxisRaw("Vertical"); moveNorm = new Vector2(xMove, yMove); moveNorm.Normalize (); }
/* // Use this for initialization void Start () { } */ /* // Update is called once per frame void Update () { } */ public void Smash(Vector2 dir) { dir.Normalize(); dir *= 100f; for(int i=0; i<5; ++i) { GameObject temp = OT.CreateObject("particle"); OTSprite particle = temp.GetComponent<OTSprite>(); particle.transform.parent = ParticlesContainer.transform; particle.position = GetComponent<OTSprite>().position; Vector2 dirTemp = CreatureManager.RotateDeg(dir, Random.Range(-30f, 30f)); particle.rigidbody.AddForce(dirTemp.x, dirTemp.y, 0, ForceMode.Impulse); OTTween tween = new OTTween(particle, 2f, OTEasing.Linear); tween.TweenAdd("rotation", Random.Range(100f, 1000f)); OT.Destroy(particle, 2f); } OTSprite destructible = GetComponent<OTSprite>(); OTTween tween2 = new OTTween(destructible, 0.5f, OTEasing.Linear); tween2.TweenAdd("alpha", -1f); destructible.collidable = false; OT.Destroy(destructible, 0.5f); }
void Shoot(Vector2 direction) { if(shotTimer <= 0.0f){ GameAudio.that.playShoot(); shotTimer = shotDelay; direction.Normalize(); Vector3 pos = transform.position + new Vector3(direction.x * 0.8f, direction.y * 0.8f, 0.0f); GameObject bullet = (GameObject) Instantiate(Resources.Load("Bullet"), pos, Quaternion.identity) ; bullet.rigidbody2D.velocity = direction; if(fireMode == FireMode.SPRAY) { bullet = (GameObject) Instantiate(Resources.Load("Bullet"), pos, Quaternion.identity) ; float theta = thetaSpread * Mathf.Deg2Rad; Vector3 dir = new Vector3(0,0,0); dir.x = direction.x * Mathf.Cos(theta) - direction.y * Mathf.Sin (theta); dir.y = direction.x * Mathf.Sin(theta) + direction.y * Mathf.Cos(theta); bullet.rigidbody2D.velocity = dir; bullet = (GameObject) Instantiate(Resources.Load("Bullet"), pos, Quaternion.identity) ; theta = -thetaSpread * Mathf.Deg2Rad; dir.x = direction.x * Mathf.Cos(theta) - direction.y * Mathf.Sin (theta); dir.y = direction.x * Mathf.Sin(theta) + direction.y * Mathf.Cos(theta); bullet.rigidbody2D.velocity = dir; } } }
void GetInput() { Vector2 input = new Vector2 (Input.GetAxis("Horizontal"), Input.GetAxis("Vertical")); if (input.sqrMagnitude > 1f) { input.Normalize(); } input *= deltaTime * 10f * movementSpeed; if (Input.GetButton("Super Speed")) { input *= superSpeedMultiplier; } Vector3 targetMovementPosition = transform.position + cameraContainer.right * input.x + cameraContainer.forward * input.y; targetMovementPosition = Vector3.Lerp(transform.position, targetMovementPosition, deltaTime / movementSmoothing); targetMovementPosition.x = Mathf.Clamp(targetMovementPosition.x, -clampedLimits.x, clampedLimits.x); targetMovementPosition.z = Mathf.Clamp(targetMovementPosition.z, -clampedLimits.y, clampedLimits.y); // transform.position = targetMovementPosition; UpdateHeightSettings(targetMovementPosition); float zoom = Input.mouseScrollDelta.y * -50f * deltaTime * zoomSpeed; Vector3 targetPosition = new Vector3(targetMovementPosition.x, Mathf.Clamp(targetMovementPosition.y + zoom, zoomRange.x, zoomRange.y), targetMovementPosition.z); transform.position = Vector3.Lerp(targetMovementPosition, targetPosition, deltaTime / zoomSmoothing); }
void FixedUpdate() { // check to see if player is grounded Vector3 castStart = transform.position + new Vector3(0.0f, 0.5f, 0.0f); RaycastHit info; grounded = Physics.SphereCast(castStart, 0.25f, Vector3.down, out info, 0.5f); float inputX = Input.GetAxisRaw("Horizontal"); float inputY = Input.GetAxisRaw("Vertical"); Vector2 input = new Vector2(inputX, inputY); if (input.sqrMagnitude > 1.0f) { input.Normalize(); } Vector3 xzforward = Vector3.Cross(Vector3.up, -cam.right).normalized; timeSinceJump += Time.deltaTime; if (Input.GetButtonDown("Jump")) { timeSinceJump = 0.0f; } float newY = rb.velocity.y; if (timeSinceJump < 0.25f && grounded) { newY = jumpSpeed; grounded = false; //hasLanded = false; } Vector3 xzright = cam.right; xzright.y = 0.0f; xzright.Normalize(); rb.velocity = (input.x * xzright + input.y * xzforward) * moveSpeed + newY * Vector3.up; }
private Vector2 CalculateBottomState(Vector2 P_before, Vector2 P_mid, Vector2 P_after) { Vector2 P_diff = (P_after - P_before); Vector2 P_hat = new Vector2(-P_diff.y, P_diff.x); P_hat.Normalize(); return P_mid - P_hat * lineWidth; }
public void Move (Vector2 delta) { delta.Normalize (); delta *= speed * Time.deltaTime; Vector3 targetPosition = transform.position + (Vector3)delta; lastMovement = delta; totalWalk += delta.magnitude; if (footTrail && totalWalk > distanceForFootstep) { string footString = leftFoot ? "Prefabs/FootStepL" : "Prefabs/FootStepR"; Vector3 pos = transform.position; if (Mathf.Abs (delta.y) > Mathf.Abs (delta.x)) { pos.x += leftFoot ? 0.3f : -0.3f; } leftFoot = !leftFoot; pos.z = footStepZPos; GameObject foot = Instantiate (Resources.Load <GameObject> (footString), pos, Quaternion.identity) as GameObject; SFX.PlayFootStep (); Vector3 euler = foot.transform.eulerAngles; euler.z =-GameMath.Angle (delta); foot.transform.eulerAngles = euler; totalWalk = 0; } rigidBody2D.MovePosition (targetPosition); }
// Update is called once per frame void FixedUpdate () { if (moveBody != null && targetWaypoint < waypoints.Length) { Vector2 oldWayPos; if (targetWaypoint == 0) oldWayPos = Vector2.zero; else oldWayPos = new Vector2(waypoints[targetWaypoint - 1].x, waypoints[targetWaypoint - 1].y); Vector2 newPosition = new Vector2(waypoints[targetWaypoint].x, waypoints[targetWaypoint].y) - oldWayPos; if (isMoving)//We are on way from one waypoint to another, shouldn't miss it { if ((moveBody.position - oldPosition).SqrMagnitude() > newPosition.SqrMagnitude()) { isMoving = false; //moveBody.velocity = Vector2.zero; targetWaypoint++; } } else//Let's find another waypoint! { oldPosition = moveBody.position; newPosition.Normalize(); Vector2 velocity = newPosition * waypoints[targetWaypoint].z; moveBody.velocity = velocity; isMoving = true; } } }
void Start() { lateralDirection = Vector3.Cross(Vector3.back, direction); lateralDirection *= Random.Range(-1f, 1f); lateralDirection.Normalize(); creationTime = Time.time; }
Quaternion Calculate() { dif=aim.position - turret.position; dif.Normalize (); float rotZ = Mathf.Atan2 (dif.y, dif.x) * Mathf.Rad2Deg; return Quaternion.Euler (new Vector3(0.0f,0.0f,rotZ)); }
Vector2 Plot (Vector2 from, Vector2 to, Ship target = null) { Vector2 relPos = to-from; RaycastHit2D firstRay = Physics2D.CircleCast (from, cRadius, relPos, Mathf.Infinity, layerMask); if (!firstRay) { return to; } if (target && firstRay.transform.gameObject.Equals(target.gameObject)) { return to; } Vector2 silly = new Vector2 (relPos.y, -relPos.x); silly.Normalize (); Vector2 newPos = firstRay.centroid; float distance = relPos.magnitude / 2; for (int i = 1; i < maxIterations; i++) { newPos = newPos+silly*Mathf.Pow (-1, i)*i*7; RaycastHit2D iterRay = Physics2D.CircleCast (from, cRadius, newPos-from, distance, layerMask); if (!iterRay.collider || target && iterRay.transform.gameObject.Equals (target.gameObject)) { return from+(newPos-from).normalized*distance; } } return from + firstRay.normal*30; }
// Update is called once per frame public override void Update() { if (GetComponent<NetworkView> ().isMine && gameController.GetComponent<GameController> ().InputEnabled && isNotFucked) { //Movement shiat move = new Vector2 (Input.GetAxis ("Horizontal"), Input.GetAxis ("Vertical")); move.Normalize (); if (Strike >= 0) { --Strike; } else { Strike = Input.GetMouseButtonDown (0) ? 6 : -1; } if (anim && Strike >= 0) { //Swing Weapon Here anim.SetBool ("Strike", Strike != 0); networkView.RPC ("SetStrike", RPCMode.AllBuffered, Strike); } base.Update (); } if (!isNotFucked) { UpdateStunnedStuff (); } }
/// <summary> /// Define the variables that control the diraction of the player /// </summary> /// <param name="player">The player</param> public void setupDirection(Player player) { if (Input.GetKey(KeyCode.Mouse0)) { lastTimeWithMouse = Time.time; /// GET THE DIRECTION WITH THE MOUSE Camera camera = Camera.main; Vector3 pos = camera.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, camera.nearClipPlane)); deltaDirection = pos - player.transform.position; deltaDirection.Normalize(); deadDirection = deltaDirection; } else if (lastTimeWithMouse < Time.time - .3f) { // Check if passed 0.2 seconds after the last mouse input /// GET THE DIRECTION WITH THE AXIS deltaDirection = new Vector2(Input.GetAxis("Horizontal"), Input.GetAxis("Vertical")); if (deltaDirection.magnitude > 1) deltaDirection.Normalize(); if (deltaDirection.magnitude > 0.2f) deadDirection = deltaDirection; else deltaDirection = Vector2.zero; } else { deltaDirection = Vector2.zero; } Direction = LockDirection != Vector2.zero ? LockDirection : deadDirection; InMoving = deltaDirection != Vector2.zero; }
void DetectMobileInput() { if (Input.touchCount == 0 ) return; Touch touch = Input.GetTouch(0); if (touch.phase == TouchPhase.Began) firstInput = new Vector2(touch.position.x, touch.position.y); if (touch.phase == TouchPhase.Ended) { lastInput = new Vector2(touch.position.x, touch.position.y); currentSwipe = new Vector2(lastInput.x - firstInput.x, lastInput.y - firstInput.y); if (currentSwipe.magnitude < minSwipeLength) return; currentSwipe.Normalize(); if (Swipe != null) Swipe(firstInput, lastInput, currentSwipe); if (currentSwipe.y != 0 && currentSwipe.x > -0.5f && currentSwipe.x < 0.5f) { if (Swipe_Vertical != null) Swipe_Vertical(firstInput, lastInput); } else if (currentSwipe.x != 0 && currentSwipe.y > -0.5f && currentSwipe.y < 0.5f) { if (Swipe_Horizontal != null) Swipe_Horizontal(firstInput, lastInput); } } }
public void UpdateVisual(){ if (entity.dir == Vector2.zero) return; RenderersOff (); float angle = Vector2.Angle (Vector2.up, entity.dir.normalized); angle = (Mathf.Round(angle/ 45f ) * 45f); if (entity.leftOrRight == -1) { angle = 360 - angle; } var shootDirection = new Vector2(Mathf.Sin(Mathf.Deg2Rad * angle), Mathf.Cos(Mathf.Deg2Rad * angle)); shootDirection.Normalize (); float mag = shootDirection.magnitude; Vector2 dir = shootDirection; if (dir == L) { //L left.renderer.enabled = true; } else if (dir == R) { //R right.renderer.enabled = true; } else if (dir == TL) { //TL topLeft.renderer.enabled = true; } else if (dir == TR) { // TR topRight.renderer.enabled = true; } else if (dir == BL) { // BL bottomLeft.renderer.enabled = true; } else if (dir == BR) { //BR bottomRight.renderer.enabled = true; } else if (dir == U) {//UP up.renderer.enabled = true; } else if (dir == D) {//DOWN down.renderer.enabled = true; } }
protected override void TickCore(Entity host, RealmTime time, ref object state) { ProtectState s; if (state == null) s = ProtectState.DontKnowWhere; else s = (ProtectState) state; Status = CycleStatus.NotStarted; if (host.HasConditionEffect(ConditionEffectIndex.Paralyzed)) return; Entity entity = host.GetNearestEntity(acquireRange, protectee); Vector2 vect; switch (s) { case ProtectState.DontKnowWhere: if (entity != null) { s = ProtectState.Protecting; goto case ProtectState.Protecting; } break; case ProtectState.Protecting: if (entity == null) { s = ProtectState.DontKnowWhere; break; } vect = new Vector2(entity.X - host.X, entity.Y - host.Y); if (vect.Length > reprotectRange) { Status = CycleStatus.InProgress; vect.Normalize(); float dist = host.GetSpeed(speed)*(time.thisTickTimes/1000f); host.ValidateAndMove(host.X + vect.X*dist, host.Y + vect.Y*dist); host.UpdateCount++; } else { Status = CycleStatus.Completed; s = ProtectState.Protected; } break; case ProtectState.Protected: if (entity == null) { s = ProtectState.DontKnowWhere; break; } Status = CycleStatus.Completed; vect = new Vector2(entity.X - host.X, entity.Y - host.Y); if (vect.Length > protectionRange) { s = ProtectState.Protecting; goto case ProtectState.Protecting; } break; } state = s; }
private Vector2 GetRadomVelocity() { Random r = new Random(); Vector2 Direction = new Vector2(r.Next(0, 100), r.Next(0, 100)); Direction.Normalize(); return Direction * this.EnemySpeed; }
public void circleFlock(GameObject player, float radius) { Vector2 diff = player.transform.position - this.transform.position; Vector2 separation = new Vector2 (0, 0); foreach (GameObject o in GameObject.FindGameObjectsWithTag("Enemy")) { Enemy e = (Enemy) o.GetComponent("Enemy"); // Debug.Log(e); if(e.flockID == flockID) { Vector2 tmp = e.transform.position - this.transform.position; if(tmp.magnitude < 1.5f) separation += tmp; } } separation *= -1; separation.Normalize (); if(diff.magnitude > radius) { this.Move(diff + separation); } else { Vector2 tan = Vector3.Cross(diff, Vector3.forward); this.Move(tan); } this.Target(player.transform.position); }
void SmallDelay() { target = GameObject.Find ("Character").transform.position; direction = new Vector2 (target.x - transform.position.x, target.y - transform.position.y); direction.Normalize (); GetComponent<Rigidbody2D> ().velocity = direction * Random.Range (3.0f, 5.0f); }
public override Mesh BuildMesh() { MeshBuilder meshBuilder = new MeshBuilder(); float heightInc = m_Height / m_HeightSegmentCount; //calculate the slope of the cylinder based on the height and difference between radii: Vector2 slope = new Vector2(m_RadiusEnd - m_RadiusStart, m_Height); slope.Normalize(); //build the rings: for (int i = 0; i <= m_HeightSegmentCount; i++) { //centre position of this ring: Vector3 centrePos = Vector3.up * heightInc * i; //V coordinate is based on height: float v = (float)i / m_HeightSegmentCount; //interpolate between the radii: float radius = Mathf.Lerp(m_RadiusStart, m_RadiusEnd, (float)i / m_HeightSegmentCount); //build the ring: BuildRing(meshBuilder, m_RadialSegmentCount, centrePos, radius, v, i > 0, Quaternion.identity, slope); } return meshBuilder.CreateMesh(); }
private Vector2 EnsurePlayerNeverMovesFasterThanMaxSpeed(Vector2 axis) { if (Mathf.Abs (axis.magnitude) >= 1) { axis.Normalize (); } return axis; }
public override void Update(GameTime gameTime) { base.Update(gameTime); MouseState mouseState = Mouse.GetState(); deltaMousePos = new Point(mouseState.X - mousePosition.X, mouseState.Y - mousePosition.Y); mousePosition.X = mouseState.X; mousePosition.Y = mouseState.Y; deltaScroll = mouseState.ScrollWheelValue - mouseScrollValue; mouseScrollValue = mouseState.ScrollWheelValue; leftMouseDown = mouseState.LeftButton == ButtonState.Pressed; rightMouseDown = mouseState.RightButton == ButtonState.Pressed; prevState = curState; curState = Keyboard.GetState(); int posX = (curState.IsKeyDown(Keys.D) || curState.IsKeyDown(Keys.Right)) ? 1 : 0; int negX = (curState.IsKeyDown(Keys.A) || curState.IsKeyDown(Keys.Left)) ? -1 : 0; int posY = (curState.IsKeyDown(Keys.W) || curState.IsKeyDown(Keys.Up)) ? 1 : 0; int negY = (curState.IsKeyDown(Keys.S) || curState.IsKeyDown(Keys.Down)) ? -1 : 0; movementDir = new Vector2(posX + negX, posY + negY); if (movementDir != Vector2.Zero) movementDir.Normalize(); spaceBarPressed = curState.IsKeyDown(Keys.Space) && prevState.IsKeyUp(Keys.Space); shiftDown = curState.IsKeyDown(Keys.LeftShift) || curState.IsKeyDown(Keys.RightShift); shiftUp = curState.IsKeyUp(Keys.LeftShift) && curState.IsKeyUp(Keys.RightShift); enterDown = curState.IsKeyDown(Keys.Enter); escapeDown = curState.IsKeyDown(Keys.Escape); }
//Updates movement, rotation. public void AIUpdate(float hor, float ver) { if (Random.Range(0, 100) < 20) { print("stop"); _movement = new Vector2(0, 0); } else { _movement = new Vector2(hor, ver); _movement.Normalize(); } _rigidbody.velocity = _movement * _fMoveSpeed; if (lastMoveHor != hor || lastMoveVer != ver) { AIPlayer player = GetComponent<AIPlayer>(); //player.makeDecision(0, 0.01f); } lastMoveHor = hor; lastMoveVer = ver; float angle = Mathf.Atan2(-hor, ver) * Mathf.Rad2Deg; transform.rotation = Quaternion.Euler(0, 0, angle); }
// The AI of the projectile public override void AI() { Vector2 mousePos = Main.MouseWorld; Player player = Main.player[projectile.owner]; #region Set projectile position // Multiplayer support here, only run this code if the client running it is the owner of the projectile if (projectile.owner == Main.myPlayer) { Vector2 diff = mousePos - player.Center; diff.Normalize(); projectile.velocity = diff; projectile.direction = Main.MouseWorld.X > player.position.X ? 1 : -1; projectile.netUpdate = true; projectile.soundDelay--; //added sound } projectile.position = player.Center + projectile.velocity * MoveDistance; projectile.timeLeft = 2; int dir = projectile.direction; player.ChangeDir(dir); player.heldProj = projectile.whoAmI; player.itemTime = 2; player.itemAnimation = 2; player.itemRotation = (float)Math.Atan2(projectile.velocity.Y * dir, projectile.velocity.X * dir); #endregion #region Charging process // Kill the projectile if the player stops channeling if (!player.channel) { projectile.Kill(); } else { // Do we still have enough mana? If not, we kill the projectile because we cannot use it anymore if (Main.time % 10 < 1 && !player.HasAmmo(player.inventory[player.selectedItem], true)) //(player.inventory[player.selectedItem], true)) //if (Main.time % 10 < 1 && !player.HasAmmo(player.inventory[ItemType<Items.Companion.Ranger.Tier8.PulseAmmo>()], true)) //(player.inventory[player.selectedItem], true)) { projectile.Kill(); } Vector2 offset = projectile.velocity; offset *= MoveDistance - 20; Vector2 pos = player.Center + offset - new Vector2(10, 10); if (Charge < MaxChargeValue) { Charge++; } int chargeFact = (int)(Charge / 20f); Vector2 dustVelocity = Vector2.UnitX * 18f; dustVelocity = dustVelocity.RotatedBy(projectile.rotation - 1.57f, default(Vector2)); Vector2 spawnPos = projectile.Center + dustVelocity; for (int k = 0; k < chargeFact + 1; k++) { Vector2 spawn = spawnPos + ((float)Main.rand.NextDouble() * 6.28f).ToRotationVector2() * (12f - (chargeFact * 2)); Dust dust = Main.dust[Dust.NewDust(pos, 20, 20, 223, projectile.velocity.X / 2f, projectile.velocity.Y / 2f, 0, default(Color), 1f)];//dust is 226 dust.velocity = Vector2.Normalize(spawnPos - spawn) * 1.5f * (10f - chargeFact * 2f) / 10f; dust.noGravity = true; dust.scale = Main.rand.Next(10, 20) * 0.05f; } } #endregion #region Set laser tail position and dusts if (Charge < MaxChargeValue) { return; } Vector2 start = player.Center; Vector2 unit = projectile.velocity; unit *= -1; for (Distance = MoveDistance; Distance <= 2200f; Distance += 5f) { start = player.Center + projectile.velocity * Distance; if (!Collision.CanHit(player.Center, 1, 1, start, 1, 1)) { Distance -= 5f; break; } if (projectile.soundDelay <= 0) //this is the proper sound delay for this type of weapon { Main.PlaySound(SoundID.Item, (int)projectile.Center.X, (int)projectile.Center.Y, 15); //this is the sound when the weapon is used cheange 15 for diferent sound projectile.soundDelay = 40; //this is the proper sound delay for this type of weapon if (Main.rand.NextFloat() < .75f) //has a 75% chance to consume ammo. { player.ConsumeItem(ItemType <Items.Companion.Ranger.Tier8.PulseAmmo>(), true); } } } Vector2 dustPos = player.Center + projectile.velocity * Distance; //Imported dust code from source because I'm lazy for (int i = 0; i < 2; ++i) { float num1 = projectile.velocity.ToRotation() + (Main.rand.Next(2) == 1 ? -1.0f : 1.0f) * 1.57f; float num2 = (float)(Main.rand.NextDouble() * 0.8f + 1.0f); Vector2 dustVel = new Vector2((float)Math.Cos(num1) * num2, (float)Math.Sin(num1) * num2); Dust dust = Main.dust[Dust.NewDust(dustPos, 0, 0, 223, dustVel.X, dustVel.Y, 0, new Color(), 1f)]; //dust is 226 dust.noGravity = true; dust.scale = 1.2f; dust = Dust.NewDustDirect(Main.player[projectile.owner].Center, 0, 0, 31, -unit.X * Distance, -unit.Y * Distance); dust.fadeIn = 0f; dust.noGravity = true; dust.scale = 0.88f; dust.color = Color.Cyan; } if (Main.rand.Next(5) == 0) { Vector2 offset = projectile.velocity.RotatedBy(1.57f, new Vector2()) * ((float)Main.rand.NextDouble() - 0.5f) * projectile.width; Dust dust = Main.dust[ Dust.NewDust(dustPos + offset - Vector2.One * 4f, 8, 8, 231, 0.0f, 0.0f, 100, new Color(), 1.5f)]; //dust is 31 dust.velocity = dust.velocity * 0.5f; dust.velocity.Y = -Math.Abs(dust.velocity.Y); unit = dustPos - Main.player[projectile.owner].Center; unit.Normalize(); dust = Main.dust[ Dust.NewDust(Main.player[projectile.owner].Center + 55 * unit, 8, 8, 134, 0.0f, 0.0f, 100, new Color(), 1.5f)]; dust.velocity = dust.velocity * 0.5f; dust.velocity.Y = -Math.Abs(dust.velocity.Y); } #endregion //Add lights DelegateMethods.v3_1 = new Vector3(0.8f, 0.8f, 1f); Utils.PlotTileLine(projectile.Center, projectile.Center + projectile.velocity * (Distance - MoveDistance), 26, DelegateMethods.CastLight); }
public override void AI() { Player target = Main.player[(int)projectile.ai[0]]; projectile.localAI[0]++; switch ((int)projectile.ai[1]) { case 0: //true eye movement code Vector2 newVel = target.Center - projectile.Center + new Vector2(-200f, -200f); if (newVel != Vector2.Zero) { newVel.Normalize(); newVel *= 24f; projectile.velocity.X = (projectile.velocity.X * 29 + newVel.X) / 30; projectile.velocity.Y = (projectile.velocity.Y * 29 + newVel.Y) / 30; } if (projectile.Distance(target.Center) < 150f) { if (projectile.Center.X < target.Center.X) projectile.velocity.X -= 0.25f; else projectile.velocity.X += 0.25f; if (projectile.Center.Y < target.Center.Y) projectile.velocity.Y -= 0.25f; else projectile.velocity.Y += 0.25f; } if (projectile.localAI[0] > 60f) { projectile.localAI[0] = 0f; projectile.ai[1]++; projectile.netUpdate = true; } break; case 1: //slow down projectile.velocity *= 0.9f; if (projectile.velocity.Length() < 1f) //stop, FIRE LASER { projectile.velocity = Vector2.Zero; projectile.localAI[0] = 0f; projectile.ai[1]++; projectile.netUpdate = true; } break; case 2: //shoot if (projectile.localAI[0] == 7f) { Main.PlaySound(4, (int)projectile.Center.X, (int)projectile.Center.Y, 6, 1f, 0.0f); ShootBolts(target); } else if (projectile.localAI[0] == 14f) { ShootBolts(target); } else if (projectile.localAI[0] > 21f) { projectile.localAI[0] = 0f; projectile.ai[1]++; } break; default: for (int i = 0; i < 30; i++) { int d = Dust.NewDust(projectile.position, projectile.width, projectile.height, 135, 0f, 0f, 0, default(Color), 3f); Main.dust[d].noGravity = true; Main.dust[d].noLight = true; Main.dust[d].velocity *= 8f; } Main.PlaySound(29, (int)projectile.Center.X, (int)projectile.Center.Y, 102, 1f, 0.0f); projectile.Kill(); break; } if (projectile.rotation > 3.14159274101257) projectile.rotation = projectile.rotation - 6.283185f; projectile.rotation = projectile.rotation <= -0.005 || projectile.rotation >= 0.005 ? projectile.rotation * 0.96f : 0.0f; if (++projectile.frameCounter >= 4) { projectile.frameCounter = 0; if (++projectile.frame >= Main.projFrames[projectile.type]) projectile.frame = 0; } if (projectile.ai[1] != 2f) //custom pupil when attacking UpdatePupil(); }
/// <summary> /// Lets the game respond to player input. Unlike the Update method, /// this will only be called when the gameplay screen is active. /// </summary> public override void HandleInput(GameTime gameTime, InputState input) { if (input == null) { throw new ArgumentNullException("input"); } // Look up inputs for the active player profile. int playerIndex = (int)ControllingPlayer.Value; KeyboardState keyboardState = input.CurrentKeyboardStates[playerIndex]; GamePadState gamePadState = input.CurrentGamePadStates[playerIndex]; // The game pauses either if the user presses the pause button, or if // they unplug the active gamepad. This requires us to keep track of // whether a gamepad was ever plugged in, because we don't want to pause // on PC if they are playing with a keyboard and have no gamepad at all! bool gamePadDisconnected = !gamePadState.IsConnected && input.GamePadWasConnected[playerIndex]; PlayerIndex player; if (pauseAction.Evaluate(input, ControllingPlayer, out player) || gamePadDisconnected) { #if WINDOWS_PHONE ScreenManager.AddScreen(new PhonePauseScreen(), ControllingPlayer); #else ScreenManager.AddScreen(new PauseMenuScreen(), ControllingPlayer); #endif } else { // Otherwise move the player position. Vector2 movement = Vector2.Zero; if (keyboardState.IsKeyDown(Keys.Left)) { movement.X--; } if (keyboardState.IsKeyDown(Keys.Right)) { movement.X++; } if (keyboardState.IsKeyDown(Keys.Up)) { movement.Y--; } if (keyboardState.IsKeyDown(Keys.Down)) { movement.Y++; } Vector2 thumbstick = gamePadState.ThumbSticks.Left; movement.X += thumbstick.X; movement.Y -= thumbstick.Y; if (movement.Length() > 1) { movement.Normalize(); } playerPosition += movement * 8f; } }
// Update is called once per frame void Update() { horizontal = Input.GetAxis("Horizontal"); vertical = Input.GetAxis("Vertical"); Vector2 move = new Vector2(horizontal, vertical); if (!Mathf.Approximately(move.x, 0.0f) || !Mathf.Approximately(move.y, 0.0f)) { lookDirection.Set(move.x, move.y); lookDirection.Normalize(); } animator.SetFloat("Look X", lookDirection.x); animator.SetFloat("Look Y", lookDirection.y); animator.SetFloat("Speed", move.magnitude); if (isInvincible) { invincibleTimer -= Time.deltaTime; if (invincibleTimer < 0) { isInvincible = false; } } if (canShoot == 1) { if (Input.GetKeyDown(KeyCode.C)) { Launch(); } } if (Input.GetKeyDown(KeyCode.X)) { RaycastHit2D hit = Physics2D.Raycast(rigidbody2d.position + Vector2.up * 0.2f, lookDirection, 1.5f, LayerMask.GetMask("Door")); if (hit.collider != null) { scr_door door = hit.collider.GetComponent <scr_door>(); if (door != null) { if (key >= 1) { door.OpenDoor(); key--; } } } } if (currentHealth <= 0) { if (lives == 0) { SceneManager.LoadScene(sceneName: "Lose"); } currentHealth = maxHealth; SceneReload(); } if (canShoot >= 1) { canShoot = 1; } }
partial void UpdateNetInput() { if (GameMain.Client != null) { if (this != Controlled) { //freeze AI characters if more than 1 seconds have passed since last update from the server if (lastRecvPositionUpdateTime < NetTime.Now - 1.0f) { AnimController.Frozen = true; memState.Clear(); //hide after 2 seconds if (lastRecvPositionUpdateTime < NetTime.Now - 2.0f) { Enabled = false; return; } } } else { var posInfo = new CharacterStateInfo( SimPosition, AnimController.Collider.Rotation, LastNetworkUpdateID, AnimController.TargetDir, SelectedCharacter, SelectedConstruction, AnimController.Anim); memLocalState.Add(posInfo); InputNetFlags newInput = InputNetFlags.None; if (IsKeyDown(InputType.Left)) { newInput |= InputNetFlags.Left; } if (IsKeyDown(InputType.Right)) { newInput |= InputNetFlags.Right; } if (IsKeyDown(InputType.Up)) { newInput |= InputNetFlags.Up; } if (IsKeyDown(InputType.Down)) { newInput |= InputNetFlags.Down; } if (IsKeyDown(InputType.Run)) { newInput |= InputNetFlags.Run; } if (IsKeyDown(InputType.Crouch)) { newInput |= InputNetFlags.Crouch; } if (IsKeyHit(InputType.Select)) { newInput |= InputNetFlags.Select; //TODO: clean up the way this input is registered } if (IsKeyHit(InputType.Deselect)) { newInput |= InputNetFlags.Deselect; } if (IsKeyHit(InputType.Health)) { newInput |= InputNetFlags.Health; } if (IsKeyHit(InputType.Grab)) { newInput |= InputNetFlags.Grab; } if (IsKeyDown(InputType.Use)) { newInput |= InputNetFlags.Use; } if (IsKeyDown(InputType.Aim)) { newInput |= InputNetFlags.Aim; } if (IsKeyDown(InputType.Shoot)) { newInput |= InputNetFlags.Shoot; } if (IsKeyDown(InputType.Attack)) { newInput |= InputNetFlags.Attack; } if (IsKeyDown(InputType.Ragdoll)) { newInput |= InputNetFlags.Ragdoll; } if (AnimController.TargetDir == Direction.Left) { newInput |= InputNetFlags.FacingLeft; } Vector2 relativeCursorPos = cursorPosition - AimRefPosition; relativeCursorPos.Normalize(); UInt16 intAngle = (UInt16)(65535.0 * Math.Atan2(relativeCursorPos.Y, relativeCursorPos.X) / (2.0 * Math.PI)); NetInputMem newMem = new NetInputMem { states = newInput, intAim = intAngle }; if (focusedItem != null && !CharacterInventory.DraggingItemToWorld && (!newMem.states.HasFlag(InputNetFlags.Grab) && !newMem.states.HasFlag(InputNetFlags.Health))) { newMem.interact = focusedItem.ID; } else if (focusedCharacter != null) { newMem.interact = focusedCharacter.ID; } memInput.Insert(0, newMem); LastNetworkUpdateID++; if (memInput.Count > 60) { memInput.RemoveRange(60, memInput.Count - 60); } } } else //this == Character.Controlled && GameMain.Client == null { AnimController.Frozen = false; } }
/// <summary> /// Allows the game to run logic such as updating the world, /// checking for collisions, gathering input, and playing audio. /// </summary> /// <param name="gameTime">Provides a snapshot of timing values.</param> protected override void Update(GameTime gameTime) { // Allows the game to exit if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed) { this.Exit(); } // TODO: Add your update logic here switch (gameState) { case GameStates.TitleScreen: KeyboardState kb = Keyboard.GetState(); if (kb.IsKeyDown(Keys.Space)) { gameState = GameStates.Playing; } break; case GameStates.Playing: ball.Velocity += new Vector2(0, 55); MouseState ms = Mouse.GetState(); Vector2 clk = new Vector2(ms.X, ms.Y); if ((ms.LeftButton == ButtonState.Pressed && Vector2.Distance(clk, ball.Center) < ball.BoundingBoxRect.Width / 2 && ball.Velocity.Y > 0)) { ball.Velocity *= new Vector2(1, -1); Vector2 move = ball.Center - clk; move.Normalize(); move *= 300; // Scale the vector by the speed you want move.Y = -150; // Set the ball.Velocity += move; score++; } if (ball.Location.Y > this.Window.ClientBounds.Height - ball.BoundingBoxRect.Height) { //ball.Velocity *= new Vector2(1, -1); gameState = GameStates.Gameover; } // Enforce a maximum speed Vector2 vel = ball.Velocity; float speed = vel.Length(); vel.Normalize(); vel *= MathHelper.Clamp(speed, 0, 1200); ball.Velocity = vel; ball.Update(gameTime); break; case GameStates.FailedAtLife: break; case GameStates.Gameover: break; } base.Update(gameTime); }
public override void AI() { if (npc.localAI[3] == 0) //spawn friends { npc.TargetClosest(false); npc.localAI[3] = 1; /*if (npc.Distance(Main.player[npc.target].Center) < 1500) * { * npc.localAI[3] = 1; * } * else * { * Movement(Main.player[npc.target].Center, 0.8f, 32f); * return; * }*/ if (Main.netMode != NetmodeID.MultiplayerClient) { int n = NPC.NewNPC((int)npc.Center.X, (int)npc.Center.Y, ModContent.NPCType <NatureChampionHead>(), npc.whoAmI, 0f, npc.whoAmI, 0f, -3f, npc.target); if (n != Main.maxNPCs) { heads[0] = n; Main.npc[n].velocity.X = Main.rand.NextFloat(-24f, 24f); Main.npc[n].velocity.Y = Main.rand.NextFloat(-24f, 24f); if (Main.netMode == NetmodeID.Server) { NetMessage.SendData(MessageID.SyncNPC, -1, -1, null, n); } } n = NPC.NewNPC((int)npc.Center.X, (int)npc.Center.Y, ModContent.NPCType <NatureChampionHead>(), npc.whoAmI, 0f, npc.whoAmI, 0f, -2f, npc.target); if (n != Main.maxNPCs) { heads[1] = n; Main.npc[n].velocity.X = Main.rand.NextFloat(-24f, 24f); Main.npc[n].velocity.Y = Main.rand.NextFloat(-24f, 24f); if (Main.netMode == NetmodeID.Server) { NetMessage.SendData(MessageID.SyncNPC, -1, -1, null, n); } } n = NPC.NewNPC((int)npc.Center.X, (int)npc.Center.Y, ModContent.NPCType <NatureChampionHead>(), npc.whoAmI, 0f, npc.whoAmI, 0f, -1f, npc.target); if (n != Main.maxNPCs) { heads[2] = n; Main.npc[n].velocity.X = Main.rand.NextFloat(-24f, 24f); Main.npc[n].velocity.Y = Main.rand.NextFloat(-24f, 24f); if (Main.netMode == NetmodeID.Server) { NetMessage.SendData(MessageID.SyncNPC, -1, -1, null, n); } } n = NPC.NewNPC((int)npc.Center.X, (int)npc.Center.Y, ModContent.NPCType <NatureChampionHead>(), npc.whoAmI, 0f, npc.whoAmI, 0f, 1f, npc.target); if (n != Main.maxNPCs) { heads[3] = n; Main.npc[n].velocity.X = Main.rand.NextFloat(-24f, 24f); Main.npc[n].velocity.Y = Main.rand.NextFloat(-24f, 24f); if (Main.netMode == NetmodeID.Server) { NetMessage.SendData(MessageID.SyncNPC, -1, -1, null, n); } } n = NPC.NewNPC((int)npc.Center.X, (int)npc.Center.Y, ModContent.NPCType <NatureChampionHead>(), npc.whoAmI, 0f, npc.whoAmI, 0f, 2f, npc.target); if (n != Main.maxNPCs) { heads[4] = n; Main.npc[n].velocity.X = Main.rand.NextFloat(-24f, 24f); Main.npc[n].velocity.Y = Main.rand.NextFloat(-24f, 24f); if (Main.netMode == NetmodeID.Server) { NetMessage.SendData(MessageID.SyncNPC, -1, -1, null, n); } } n = NPC.NewNPC((int)npc.Center.X, (int)npc.Center.Y, ModContent.NPCType <NatureChampionHead>(), npc.whoAmI, 0f, npc.whoAmI, 0f, 3f, npc.target); if (n != Main.maxNPCs) { heads[5] = n; Main.npc[n].velocity.X = Main.rand.NextFloat(-24f, 24f); Main.npc[n].velocity.Y = Main.rand.NextFloat(-24f, 24f); if (Main.netMode == NetmodeID.Server) { NetMessage.SendData(MessageID.SyncNPC, -1, -1, null, n); } } for (int i = 0; i < heads.Length; i++) //failsafe, die if couldnt spawn heads { if (heads[i] == -1 && Main.netMode != NetmodeID.MultiplayerClient) { npc.active = false; return; } } } } EModeGlobalNPC.championBoss = npc.whoAmI; Player player = Main.player[npc.target]; Vector2 targetPos; if (npc.HasValidTarget && npc.Distance(player.Center) < 3000 && player.Center.Y >= Main.worldSurface * 16 && !player.ZoneUnderworldHeight) { npc.timeLeft = 600; } if (player.Center.X < npc.position.X) { npc.direction = npc.spriteDirection = -1; } else if (player.Center.X > npc.position.X + npc.width) { npc.direction = npc.spriteDirection = 1; } switch ((int)npc.ai[0]) { case -1: //mourning wood movement { npc.noTileCollide = true; npc.noGravity = true; if (npc.position.X < player.Center.X && player.Center.X < npc.position.X + npc.width) { npc.velocity.X *= 0.92f; if (Math.Abs(npc.velocity.X) < 0.1f) { npc.velocity.X = 0f; } } else { float accel = 2f; /*if (Math.Abs(player.Center.X - npc.Center.X) > 1200) //secretly fast run * { * accel = 24f; * } * else * { * if (Math.Abs(npc.velocity.X) > 2) * npc.velocity.X *= 0.97f; * }*/ if (player.Center.X > npc.Center.X) { npc.velocity.X = (npc.velocity.X * 20 + accel) / 21; } else { npc.velocity.X = (npc.velocity.X * 20 - accel) / 21; } } bool onPlatforms = false; for (int i = (int)npc.position.X; i <= npc.position.X + npc.width; i += 16) { if (Framing.GetTileSafely(new Vector2(i, npc.position.Y + npc.height + npc.velocity.Y + 1)).type == TileID.Platforms) { onPlatforms = true; break; } } bool onCollision = Collision.SolidCollision(npc.position, npc.width, npc.height); if (npc.position.X < player.position.X && npc.position.X + npc.width > player.position.X + player.width && npc.position.Y + npc.height < player.position.Y + player.height - 16) { npc.velocity.Y += 0.5f; } else if (onCollision || (onPlatforms && player.position.Y + player.height <= npc.position.Y + npc.height)) { if (npc.velocity.Y > 0f) { npc.velocity.Y = 0f; } if (onCollision) { if (npc.velocity.Y > -0.2f) { npc.velocity.Y -= 0.025f; } else { npc.velocity.Y -= 0.2f; } if (npc.velocity.Y < -4f) { npc.velocity.Y = -4f; } } } else { if (npc.velocity.Y < 0f) { npc.velocity.Y = 0f; } if (npc.velocity.Y < 0.1f) { npc.velocity.Y += 0.025f; } else { npc.velocity.Y += 0.5f; } } if (npc.velocity.Y > 10f) { npc.velocity.Y = 10f; } } break; case 0: //think npc.noTileCollide = false; npc.noGravity = false; if (++npc.ai[1] > 45) { npc.TargetClosest(); npc.ai[0]++; npc.ai[1] = 0; npc.ai[2] = 0; npc.ai[3] = 0; npc.netUpdate = true; } goto case -1; case 1: //stomp { void StompDust() { Main.PlaySound(SoundID.Item, npc.Center, 14); for (int k = -2; k <= 2; k++) //explosions { Vector2 dustPos = npc.Center; int width = npc.width / 5; dustPos.X += width * k + Main.rand.NextFloat(-width, width); dustPos.Y += Main.rand.NextFloat(npc.height / 2); for (int i = 0; i < 30; i++) { int dust = Dust.NewDust(dustPos, 32, 32, 31, 0f, 0f, 100, default(Color), 3f); Main.dust[dust].velocity *= 1.4f; } for (int i = 0; i < 20; i++) { int dust = Dust.NewDust(dustPos, 32, 32, 6, 0f, 0f, 100, default(Color), 3.5f); Main.dust[dust].noGravity = true; Main.dust[dust].velocity *= 7f; dust = Dust.NewDust(dustPos, 32, 32, 6, 0f, 0f, 100, default(Color), 1.5f); Main.dust[dust].velocity *= 3f; } float scaleFactor9 = 0.5f; for (int j = 0; j < 4; j++) { int gore = Gore.NewGore(dustPos, default(Vector2), Main.rand.Next(61, 64)); Main.gore[gore].velocity *= scaleFactor9; Main.gore[gore].velocity.X += 1f; Main.gore[gore].velocity.Y += 1f; } } } int jumpTime = 60; if (npc.ai[3] == 1) { jumpTime = 30; } npc.noGravity = true; npc.noTileCollide = true; if (npc.ai[2] == 0) //move over player { StompDust(); npc.ai[2] = 1; npc.netUpdate = true; targetPos = player.Center; targetPos.Y -= npc.ai[3] == 1 ? 300 : 600; npc.velocity = (targetPos - npc.Center) / jumpTime; } if (++npc.ai[1] > jumpTime + (npc.ai[3] == 1 ? 1 : 18)) //do the stomp { npc.noGravity = false; npc.noTileCollide = false; if (npc.velocity.Y == 0 || npc.ai[3] == 1) //landed, now stomp { StompDust(); if (npc.ai[3] == 1) //enraged { for (int i = Main.rand.Next(2); i < heads.Length; i += 2) //activate alternating heads for deathray { if (Main.npc[heads[i]].ai[0] != 0) //don't act on a head currently doing something { continue; } Main.npc[heads[i]].ai[0] = 4f; Main.npc[heads[i]].localAI[0] = 0; Main.npc[heads[i]].ai[2] = 0; Main.npc[heads[i]].localAI[1] = 0; Main.npc[heads[i]].netUpdate = true; int glowType; switch ((int)Main.npc[heads[i]].ai[3]) { case -3: glowType = -7; break; case -2: glowType = -8; break; case -1: glowType = -9; break; case 1: glowType = -10; break; case 2: glowType = -11; break; case 3: glowType = -12; break; default: glowType = 0; break; } if (Main.netMode != NetmodeID.MultiplayerClient) { Projectile.NewProjectile(npc.Center, Vector2.Zero, ModContent.ProjectileType <Projectiles.GlowRing>(), 0, 0f, Main.myPlayer, heads[i], glowType); } } } npc.TargetClosest(); npc.ai[0]++; npc.ai[1] = npc.ai[3] == 1 ? 40 : 0; npc.ai[2] = 0; npc.ai[3] = 0; npc.netUpdate = true; } } else if (npc.ai[1] > jumpTime) //falling { if (npc.velocity.X > 2) { npc.velocity.X = 2; } if (npc.velocity.X < -2) { npc.velocity.X = -2; } npc.velocity.Y = 30f; } } break; case 2: if (!player.active || player.dead || Vector2.Distance(npc.Center, player.Center) > 3000f || player.Center.Y < Main.worldSurface * 16 || player.ZoneUnderworldHeight) //despawn code { npc.TargetClosest(false); if (npc.timeLeft > 30) { npc.timeLeft = 30; } npc.noTileCollide = true; npc.noGravity = true; npc.velocity.Y += 1f; break; } goto case 0; case 3: //decide an attack if (npc.ai[2] == 0) { void ActivateHead(int targetHead) { if (Main.npc[targetHead].ai[0] != 0) //don't act on a head currently doing something { return; } Main.npc[targetHead].ai[0] += Main.npc[targetHead].ai[3]; Main.npc[targetHead].localAI[0] = 0; Main.npc[targetHead].ai[2] = 0; Main.npc[targetHead].localAI[1] = 0; Main.npc[targetHead].netUpdate = true; Main.PlaySound(SoundID.ForceRoar, Main.npc[targetHead].Center, -1); int glowType; switch ((int)Main.npc[targetHead].ai[3]) { case -3: glowType = -7; break; case -2: glowType = -8; break; case -1: glowType = -9; break; case 1: glowType = -10; break; case 2: glowType = -11; break; case 3: glowType = -12; break; default: glowType = 0; break; } if (Main.netMode != NetmodeID.MultiplayerClient) { Projectile.NewProjectile(npc.Center, Vector2.Zero, ModContent.ProjectileType <Projectiles.GlowRing>(), 0, 0f, Main.myPlayer, targetHead, glowType); } }; npc.ai[2] = 1; npc.netUpdate = true; int set = Main.rand.Next(configurations.Length); while (heads[configurations[set].Key] == heads[configurations[lastSet].Key] || //don't reuse heads you just attacked with heads[configurations[set].Key] == heads[configurations[lastSet].Value] || heads[configurations[set].Value] == heads[configurations[lastSet].Key] || heads[configurations[set].Value] == heads[configurations[lastSet].Value]) { set = Main.rand.Next(configurations.Length); } lastSet = set; if (Main.expertMode) //activate both in expert { ActivateHead(heads[configurations[set].Key]); ActivateHead(heads[configurations[set].Value]); } else //only activate one in normal { if (Main.rand.NextBool()) { ActivateHead(heads[configurations[set].Key]); } else { ActivateHead(heads[configurations[set].Value]); } } } if (++npc.ai[1] > 300) //wait { npc.TargetClosest(); npc.ai[0]++; npc.ai[1] = 0; npc.ai[2] = 0; npc.ai[3] = 0; npc.netUpdate = true; } goto case -1; case 4: goto case 2; case 5: goto case 3; case 6: goto case 2; case 7: goto case 3; case 8: goto case 2; case 9: goto case 1; case 10: goto case 2; case 11: //deathrays if (npc.ai[2] == 0 && FargoSoulsWorld.EternityMode) { npc.ai[2] = 1; Main.PlaySound(SoundID.Roar, npc.Center, 0); for (int i = 0; i < heads.Length; i++) //activate all heads { Main.npc[heads[i]].ai[0] = 4f; Main.npc[heads[i]].localAI[0] = 0; Main.npc[heads[i]].ai[2] = 0; Main.npc[heads[i]].localAI[1] = 0; Main.npc[heads[i]].netUpdate = true; int glowType; switch ((int)Main.npc[heads[i]].ai[3]) { case -3: glowType = -7; break; case -2: glowType = -8; break; case -1: glowType = -9; break; case 1: glowType = -10; break; case 2: glowType = -11; break; case 3: glowType = -12; break; default: glowType = 0; break; } if (Main.netMode != NetmodeID.MultiplayerClient) { Projectile.NewProjectile(npc.Center, Vector2.Zero, ModContent.ProjectileType <Projectiles.GlowRing>(), 0, 0f, Main.myPlayer, heads[i], glowType); } } } if (++npc.ai[1] > 330 || !FargoSoulsWorld.EternityMode) //wait { npc.TargetClosest(); npc.ai[0]++; npc.ai[1] = 0; npc.ai[2] = 0; npc.ai[3] = 0; npc.netUpdate = true; } goto case -1; default: npc.ai[0] = 0; goto case 0; } if (FargoSoulsWorld.EternityMode) { if (npc.HasValidTarget && npc.Distance(player.Center) > 1400 && Vector2.Distance(npc.Center, player.Center) < 3000f && player.Center.Y > Main.worldSurface * 16 && !player.ZoneUnderworldHeight && npc.ai[0] > 1) // && npc.ai[0] != 9) //enrage { npc.ai[0] = 1; npc.ai[1] = 0; npc.ai[2] = 0; npc.ai[3] = 1; //marks enrage jump npc.netUpdate = true; Main.PlaySound(SoundID.ForceRoar, player.Center, -1); } Vector2 dustOffset = Vector2.Normalize(player.Center - npc.Center) * 1400; for (int i = 0; i < 20; i++) //dust ring for enrage range { int d = Dust.NewDust(npc.Center + dustOffset.RotatedByRandom(2 * Math.PI), 0, 0, 59, Scale: 2f); Main.dust[d].velocity = npc.velocity; Main.dust[d].noGravity = true; } } }
/// <summary> /// Create the cached visibility result. /// </summary> void RevealIntoCache(Revealer r, float worldToTex) { // Position relative to the fog of war Vector3 pos = r.mPos - mOrigin; // Coordinates we'll be dealing with int xmin = Mathf.RoundToInt((pos.x - r.mOuter) * worldToTex); int ymin = Mathf.RoundToInt((pos.z - r.mOuter) * worldToTex); int xmax = Mathf.RoundToInt((pos.x + r.mOuter) * worldToTex); int ymax = Mathf.RoundToInt((pos.z + r.mOuter) * worldToTex); int cx = Mathf.RoundToInt(pos.x * worldToTex); int cy = Mathf.RoundToInt(pos.z * worldToTex); cx = Mathf.Clamp(cx, 0, textureSize - 1); cy = Mathf.Clamp(cy, 0, textureSize - 1); // Create the buffer to reveal into int size = Mathf.RoundToInt(xmax - xmin); r.mCachedBuffer = new bool[size * size]; r.mCachedSize = size; r.mCachedX = xmin; r.mCachedY = ymin; // The buffer should start off clear for (int i = 0, imax = size * size; i < imax; ++i) { r.mCachedBuffer[i] = false; } int minRange = Mathf.RoundToInt(r.mInner * r.mInner * worldToTex * worldToTex); int maxRange = Mathf.RoundToInt(r.mOuter * r.mOuter * worldToTex * worldToTex); int variance = Mathf.RoundToInt(Mathf.Clamp01(margin / (heightRange.y - heightRange.x)) * 255); int gh = WorldToGridHeight(r.mPos.y); for (int y = ymin; y < ymax; ++y) { if (y > -1 && y < textureSize) { for (int x = xmin; x < xmax; ++x) { if (x > -1 && x < textureSize) { int xd = x - cx; int yd = y - cy; int dist = xd * xd + yd * yd; if (dist < minRange || (cx == x && cy == y)) { r.mCachedBuffer[(x - xmin) + (y - ymin) * size] = true; } else if (dist < maxRange) { Vector2 v = new Vector2(xd, yd); v.Normalize(); v *= r.mInner; int sx = cx + Mathf.RoundToInt(v.x); int sy = cy + Mathf.RoundToInt(v.y); if (sx > -1 && sx < textureSize && sy > -1 && sy < textureSize && IsVisible(sx, sy, x, y, Mathf.Sqrt(dist), gh, variance)) { r.mCachedBuffer[(x - xmin) + (y - ymin) * size] = true; } } } } } } }
private void UpdatePacMan(GamePadState gamePad1State, float time) { //Input for update from analog stick #region LeftStick if (gamePad1State.ThumbSticks.Left.Length() > 0.0f) { PacManDir = gamePad1State.ThumbSticks.Left; PacManDir.Y *= -1; //Invert Y Axis float RotationAngle = (float)Math.Atan2( gamePad1State.ThumbSticks.Left.X, gamePad1State.ThumbSticks.Left.Y); PacManRotate = (float)MathHelper.ToDegrees(RotationAngle - (float)(Math.PI / 2)); //Time corrected move. MOves PacMan By PacManDiv every Second PacManLoc += ((PacManDir * (time / 1000)) * PacManSpeed); //Simple Move PacMan by PacManDir } #endregion //Update for input from DPad #region DPad Vector2 PacManDDir = Vector2.Zero; if (gamePad1State.DPad.Left == ButtonState.Pressed) { //Orginal Position is Right so flip X PacManDDir += new Vector2(-1, 0); } if (gamePad1State.DPad.Right == ButtonState.Pressed) { //Original Position is Right PacManDDir += new Vector2(1, 0); } if (gamePad1State.DPad.Up == ButtonState.Pressed) { //Up PacManDDir += new Vector2(0, -1); } if (gamePad1State.DPad.Down == ButtonState.Pressed) { //Down PacManDDir += new Vector2(0, 1); } if (PacManDDir.Length() > 0) { //Angle in radians from vector float RotationAngleKey = (float)Math.Atan2( PacManDDir.X, PacManDDir.Y * -1); //Find angle in degrees PacManRotate = (float)MathHelper.ToDegrees( RotationAngleKey - (float)(Math.PI / 2)); //rotated right already //Normalize NewDir to keep agled movement at same speed as horilontal/Vert PacManDDir = Vector2.Normalize(PacManDDir); PacManDir += PacManDDir; //move the pacman PacManLoc += ((PacManDDir * (time / 1000)) * PacManSpeed); //Simple Move PacMan by PacManDir } #endregion //Update for input from Keyboard #if !XBOX360 #region KeyBoard KeyboardState keyboardState = Keyboard.GetState(); Vector2 PacManKeyDir = new Vector2(0, 0); if (keyboardState.IsKeyDown(Keys.Left)) { //Flip Horizontal PacManKeyDir += new Vector2(-1, 0); } if (keyboardState.IsKeyDown(Keys.Right)) { //No new sprite Effects PacManKeyDir += new Vector2(1, 0); } if (keyboardState.IsKeyDown(Keys.Up)) { PacManKeyDir += new Vector2(0, -1); } if (keyboardState.IsKeyDown(Keys.Down)) { PacManKeyDir += new Vector2(0, 1); } if (PacManKeyDir.Length() > 0) { float RotationAngleKey = (float)Math.Atan2( PacManKeyDir.X, PacManKeyDir.Y * -1); PacManRotate = (float)MathHelper.ToDegrees( RotationAngleKey - (float)(Math.PI / 2)); //Normalize NewDir to keep agled movement at same speed as horilontal/Vert PacManKeyDir = Vector2.Normalize(PacManKeyDir); PacManDir = PacManKeyDir; PacManLoc += ((PacManKeyDir * (time / 1000)) * PacManSpeed); //Simple Move PacMan by PacManDir } #endregion #endif //Keep PacMan On Screen if (PacManLoc.X > graphics.GraphicsDevice.Viewport.Width - (PacMan.Width / 2)) { PacManLoc.X = graphics.GraphicsDevice.Viewport.Width - (PacMan.Width / 2); } if (PacManLoc.X < (PacMan.Width / 2)) { PacManLoc.X = (PacMan.Width / 2); } if (PacManLoc.Y > graphics.GraphicsDevice.Viewport.Height - (PacMan.Height / 2)) { PacManLoc.Y = graphics.GraphicsDevice.Viewport.Height - (PacMan.Height / 2); } if (PacManLoc.Y < (PacMan.Height / 2)) { PacManLoc.Y = (PacMan.Height / 2); } //Shoot if (gamePad1State.Buttons.A == ButtonState.Pressed || Keyboard.GetState().IsKeyDown(Keys.Space)) { Shot s = new Shot(this); s.Location = PacManLoc; s.Direction = PacManDir; s.Speed = Math.Max(PacManSpeed, 1) * 4; this.Components.Add(s); } }
/// <summary> /// Reveal the map around the revealer performing line-of-sight checks. /// </summary> void RevealUsingLOS(Revealer r, float worldToTex) { // Position relative to the fog of war Vector3 pos = r.mPos - mOrigin; // Coordinates we'll be dealing with int xmin = Mathf.RoundToInt((pos.x - r.mOuter) * worldToTex); int ymin = Mathf.RoundToInt((pos.z - r.mOuter) * worldToTex); int xmax = Mathf.RoundToInt((pos.x + r.mOuter) * worldToTex); int ymax = Mathf.RoundToInt((pos.z + r.mOuter) * worldToTex); int cx = Mathf.RoundToInt(pos.x * worldToTex); int cy = Mathf.RoundToInt(pos.z * worldToTex); cx = Mathf.Clamp(cx, 0, textureSize - 1); cy = Mathf.Clamp(cy, 0, textureSize - 1); int minRange = Mathf.RoundToInt(r.mInner * r.mInner * worldToTex * worldToTex); int maxRange = Mathf.RoundToInt(r.mOuter * r.mOuter * worldToTex * worldToTex); int gh = WorldToGridHeight(r.mPos.y); int variance = Mathf.RoundToInt(Mathf.Clamp01(margin / (heightRange.y - heightRange.x)) * 255); Color32 white = new Color32(255, 255, 255, 255); for (int y = ymin; y < ymax; ++y) { if (y > -1 && y < textureSize) { for (int x = xmin; x < xmax; ++x) { if (x > -1 && x < textureSize) { int xd = x - cx; int yd = y - cy; int dist = xd * xd + yd * yd; int index = x + y * textureSize; if (dist < minRange || (cx == x && cy == y)) { mBuffer1[index] = white; } else if (dist < maxRange) { Vector2 v = new Vector2(xd, yd); v.Normalize(); v *= r.mInner; int sx = cx + Mathf.RoundToInt(v.x); int sy = cy + Mathf.RoundToInt(v.y); if (sx > -1 && sx < textureSize && sy > -1 && sy < textureSize && IsVisible(sx, sy, x, y, Mathf.Sqrt(dist), gh, variance)) { mBuffer1[index] = white; } } } } } } }
void HandleTouchInput() { Vector2 screenCharPos = Camera.main.WorldToScreenPoint(transform.position); Vector2 touchpos = screenCharPos; bool gettouch = false; #if UNITY_WEBPLAYER if (Input.GetMouseButtonDown(0)) { touchpos = Input.mousePosition; gettouch = true; } #else if (Input.touchCount > 0) { Touch t = Input.GetTouch(0); if (t.phase == TouchPhase.Began) { touchpos = t.position; gettouch = true; } } #endif if (gettouch) { Vector2 dir = touchpos - screenCharPos; dir.Normalize(); float du = Vector3.Dot(dir, Vector2.up); float dr = Vector3.Dot(dir, Vector2.right); //上. if (du >= 0) { //右. if (dr >= 0) { if (canWalkForward) { MoveValue(transform.forward); } } else { //左. if (canWalkLeft) { MoveValue(-transform.right); } } } else { //下. //右. if (dr >= 0) { if (canWalkRight) { MoveValue(transform.right); } } else { //左. if (canWalkBack) { MoveValue(-transform.forward); } } } } }
void HandleToucehDragInput() { //Vector2 screenCharPos = Camera.main.WorldToScreenPoint (transform.position); //Vector2 touchpos = screenCharPos; /* * if (Input.GetMouseButtonDown (0)) * { * beginTouchPos = Input.mousePosition; * gettouch = true; * }*/ if (Input.touchCount > 0) { Touch t = Input.GetTouch(0); if (t.phase == TouchPhase.Began) { beginTouchPos = t.position; touchBegin = true; Debug.Log("t b"); } } if (touchBegin) { bool getend = false; Vector2 endpos = Vector2.zero; if (Input.touchCount > 0) { Touch t = Input.GetTouch(0); if (t.phase == TouchPhase.Ended) { endpos = t.position; getend = true; touchBegin = false; Debug.Log("t end"); } } if (getend) { Vector2 dir = endpos - beginTouchPos; dir.Normalize(); float du = Vector2.Dot(dir, Vector2.up); float dr = Vector2.Dot(dir, Vector2.right); //上. if (du >= 0) { //右. if (dr >= 0) { if (canWalkForward) { MoveValue(transform.forward); } } else { //左. if (canWalkLeft) { MoveValue(-transform.right); } } } else { //下. //右. if (dr >= 0) { if (canWalkRight) { MoveValue(transform.right); } } else { //左. if (canWalkBack) { MoveValue(-transform.forward); } } } } } }
internal void UpdateSimulation(float a_elapsedTime) { Model.Player player = m_gameModel.m_playerSystem.m_player; Vector2 moveTo = m_gameView.GetMapMousePosition(); #region MouseMoveInteraktion float xSpeed = 0; float ySpeed = 0; Rectangle mouseRect = new Rectangle((int)moveTo.X, (int)moveTo.Y, 1, 1); if (!player.IsCastingSpell && player.IsAlive()) { if (moveTo != Vector2.Zero) //Om man håller inne (Right-mouseclick) { player.MoveToPosition = moveTo; player.Direction = new Vector2(moveTo.X - player.ThisUnit.Bounds.Center.X, moveTo.Y - player.ThisUnit.Bounds.Center.Y); } else if (player.MoveToPosition != Vector2.Zero) //Click 2 move { player.Direction = new Vector2(player.MoveToPosition.X - player.ThisUnit.Bounds.Center.X, player.MoveToPosition.Y - player.ThisUnit.Bounds.Center.Y); } Vector2 newCords = new Vector2(); Vector2 facing = new Vector2(); if (player.Direction != Vector2.Zero && !m_gameModel.m_playerSystem.ArrivedToPosition(player.ThisUnit.Bounds, player.MoveToPosition, 5)) //Om jag rör på mig { newCords = player.Direction; newCords.Normalize(); newCords.X = newCords.X * 4; newCords.Y = newCords.Y * 4; player.ThisUnit.Bounds.X += (int)newCords.X; player.ThisUnit.Bounds.Y += (int)newCords.Y; } if (player.Target != null && player.Target.ThisUnit.Bounds.Intersects(player.MaxRangeArea)) // om jag har targetat en unit så sätter jag vilket håll han ska titta åt { facing.X = player.Target.ThisUnit.Bounds.Center.X - player.ThisUnit.Bounds.Center.X; facing.Y = player.Target.ThisUnit.Bounds.Center.Y - player.ThisUnit.Bounds.Center.Y; } else { facing = newCords; } xSpeed = Math.Abs(facing.X); ySpeed = Math.Abs(facing.Y); if (facing == new Vector2()) { player.UnitState = View.AnimationSystem.FACING_CAMERA; player.WeaponState = View.AnimationSystem.MOVING_DOWN; } if (player.Target != null && player.Target.ThisUnit.Bounds.Intersects(player.MaxRangeArea)) { if (xSpeed > ySpeed) { if (facing.X > 0f) { player.UnitState = View.AnimationSystem.FACING_RIGHT; player.WeaponState = View.AnimationSystem.MOVING_RIGHT; } else { player.UnitState = View.AnimationSystem.FACING_LEFT; player.WeaponState = View.AnimationSystem.MOVING_LEFT; } } else { if (facing.Y > 0f) { player.UnitState = View.AnimationSystem.FACING_CAMERA; player.WeaponState = View.AnimationSystem.MOVING_DOWN; } else { player.UnitState = View.AnimationSystem.FACING_AWAY; player.WeaponState = View.AnimationSystem.MOVING_UP; } } } if (newCords != new Vector2() && !m_gameModel.m_playerSystem.ArrivedToPosition(player.ThisUnit.Bounds, player.MoveToPosition, 5)) { xSpeed = Math.Abs(newCords.X); ySpeed = Math.Abs(newCords.Y); if (xSpeed > ySpeed) { if (facing.X > 0f) { player.UnitState = View.AnimationSystem.MOVING_RIGHT; player.WeaponState = player.UnitState; } else { player.UnitState = View.AnimationSystem.MOVING_LEFT; player.WeaponState = player.UnitState; } } else { if (facing.Y > 0f) { player.UnitState = View.AnimationSystem.MOVING_DOWN; player.WeaponState = player.UnitState; } else { player.UnitState = View.AnimationSystem.MOVING_UP; player.WeaponState = player.UnitState; } } } } else if (player.IsCastingSpell) { player.UnitState = View.AnimationSystem.IS_CASTING_HEAL; } else { player.UnitState = View.AnimationSystem.FACING_CAMERA; } #endregion #region ActionBarInteraktion if (m_gameView.DidActivateActionBar(View.InputHandler.ACTION_BAR_TWO)) { m_gameModel.m_playerSystem.m_spellSystem.AddSpell(Model.SpellSystem.INSTANT_HEAL, player); } if (m_gameView.DidActivateActionBar(View.InputHandler.ACTION_BAR_ONE) && m_gameModel.m_playerSystem.m_player.Target != null) { if (m_gameModel.m_playerSystem.m_player.Target.GetType() == Model.GameModel.ENEMY_NPC) { m_gameModel.m_playerSystem.m_spellSystem.AddSpell(Model.SpellSystem.SMITE, player); } } if (m_gameView.DidActivateActionBar(View.InputHandler.BACKPACK)) { if (!player.BackPack.IsOpen) { player.BackPack.IsOpen = true; } else { player.BackPack.IsOpen = false; } } if (m_gameView.DidActivateActionBar(View.InputHandler.QUEST_LOG)) { if (!m_gameModel.m_questSystem.IsWatchingQuestLog) { m_gameModel.m_questSystem.IsWatchingQuestLog = true; } else { m_gameModel.m_questSystem.IsWatchingQuestLog = false; } } //Öppna stäng worldmap. if (m_gameView.DidActivateActionBar(View.InputHandler.WORLD_MAP)) { if (!player.IsLookingAtMap) { player.IsLookingAtMap = true; } else { player.IsLookingAtMap = false; } } //Öppna stäng character panel. if (m_gameView.DidActivateActionBar(View.InputHandler.CHARACTER_PANEL)) { if (!player.CharPanel.IsOpen) { player.CharPanel.IsOpen = true; } else { player.CharPanel.IsOpen = false; } } #endregion if (player.Target != null) { //Gör att spelaren slutar att attackera. if (m_gameView.UnTarget()) { player.IsAttacking = false; player.Target = null; } } #region FUSK KOD ////bli typ odödlig. //if (m_gameView.DidPressAndReleaseKey('R')) //{ // if (m_gameModel.m_playerSystem.m_player.Armor < 90) // { // m_gameModel.m_playerSystem.m_player.Armor = 100; // } //} ////FULL MANA OCH LIV. //if (m_gameView.DidPressAndReleaseKey('F')) //{ // m_gameModel.m_playerSystem.m_player.CurrentHp = m_gameModel.m_playerSystem.m_player.TotalHp; // m_gameModel.m_playerSystem.m_player.CurrentMana = m_gameModel.m_playerSystem.m_player.TotalMana; //} ////stänga på och av hinder. //if (m_gameView.DidPressAndReleaseKey('T')) //{ // if (m_gameModel.m_questSystem.CurrentQuestIndex != 2) // { // m_gameModel.m_questSystem.CurrentQuestIndex = 2; // m_gameModel.m_questSystem.CurrentQuest.Status = Model.QuestSystem.END; // } //} //if (m_gameView.DidPressAndReleaseKey('G')) //{ // foreach (Model.Enemy e in m_gameModel.m_enemySystem.m_enemies) // { // if (e.Type == Model.Enemy.BOSS_A) // { // m_gameModel.m_playerSystem.m_player.ThisUnit.Bounds.Location = e.ThisUnit.Bounds.Location; // } // } //} //if (m_gameView.DidPressAndReleaseKey('H')) //{ // foreach (Model.Friend f in m_gameModel.m_friendSystem.m_friends) // { // if (f.Type == Model.Friend.CITY_GUARD) // { // m_gameModel.m_playerSystem.m_player.ThisUnit.Bounds.Location = f.ThisUnit.Bounds.Location; // } // } //} //#region GammalKeyboardMove ////Flyttar spelaren samt bestämmer animation //if (m_gameView.DidPressKey(View.InputHandler.DOWN) && player.CanMoveDown) //{ // player.ThisUnit.Bounds.Y += Convert.ToInt32(a_elapsedTime * 200); // player.UnitState = View.AnimationSystem.MOVING_DOWN; //} //if (m_gameView.DidPressKey(View.InputHandler.UP) && player.CanMoveUp) //{ // player.ThisUnit.Bounds.Y -= Convert.ToInt32(a_elapsedTime * 200); // player.UnitState = View.AnimationSystem.MOVING_UP; //} //if (m_gameView.DidPressKey(View.InputHandler.RIGHT) && player.CanMoveRight) //{ // player.ThisUnit.Bounds.X += Convert.ToInt32(a_elapsedTime * 200); // player.UnitState = View.AnimationSystem.MOVING_RIGHT; //} //if (m_gameView.DidPressKey(View.InputHandler.LEFT) && player.CanMoveLeft) //{ // player.ThisUnit.Bounds.X -= Convert.ToInt32(a_elapsedTime * 200); // player.UnitState = View.AnimationSystem.MOVING_LEFT; //} //#endregion #endregion //Uppdaterar spelmotor m_gameModel.UpdateSimulation(a_elapsedTime); }
public static void StartHive(int i, int j) { const float strength = 2.4f; const float wallThickness = 4f; ushort fleshID = (ushort)ModContent.TileType <Riven_Flesh>(); ushort weakFleshID = (ushort)ModContent.TileType <Weak_Riven_Flesh>(); ushort fleshWallID = (ushort)ModContent.WallType <Riven_Flesh_Wall>(); lesionCount = 0; int j2 = j; if (j2 > Main.worldSurface) { j2 = (int)Main.worldSurface; } for (; !SolidTile(i, j2); j2++) { } Vector2 position = new Vector2(i, j2); for (int x = i - 30; x < i + 30; x++) { for (int y = j2 - 25; y < j2 + 15; y++) { float diff = (((y - j2) * (y - j2) * 1.5f) + (x - i) * (x - i)); if (diff > 800) { continue; } Main.tile[x, y].ResetToType(fleshID); if (diff < 750) { Main.tile[x, y].wall = fleshWallID; } } } Vector2 vector = new Vector2(0, -1).RotatedByRandom(1.6f, genRand); int distance = 0; while (Main.tile[(int)position.X, (int)position.Y].active() && Main.tileSolid[Main.tile[(int)position.X, (int)position.Y].type]) { //Main.tile[(int)position.X, (int)position.Y].ResetToType(TileID.EmeraldGemspark); //SquareTileFrame((int)position.X, (int)position.Y); position += vector; if (++distance >= 160) { break; } } vector = -vector; (Vector2 position, Vector2 velocity)last = (position, vector); //Tile t = Main.tile[(int)last.position.X, (int)last.position.Y]; (int x, int y, Vector2 direction, double length)startValues = ((int)last.position.X, (int)last.position.Y, last.velocity.RotatedByRandom(0.5f, genRand), distance *genRand.NextFloat(0.4f, 0.6f)); last = GenRunners.WalledVeinRunner(startValues.x, startValues.y, strength * genRand.NextFloat(0.9f, 1.1f), startValues.direction, startValues.length, weakFleshID, wallThickness); //t.ResetToType(TileID.AmethystGemspark); Vector2 manualVel = new Vector2(last.velocity.X, 0.2f); //t = Main.tile[(int)last.position.X, (int)last.position.Y]; GenRunners.WalledVeinRunner((int)last.position.X, (int)last.position.Y, strength * genRand.NextFloat(0.9f, 1.1f), Vector2.Normalize(new Vector2(-manualVel.X, 0.2f)), genRand.NextFloat(distance * 0.4f, distance * 0.6f) * (Math.Abs(manualVel.X) + 0.5f), weakFleshID, wallThickness, wallType: fleshWallID); last = GenRunners.WalledVeinRunner((int)last.position.X, (int)last.position.Y, strength * genRand.NextFloat(0.9f, 1.1f), Vector2.Normalize(manualVel), genRand.NextFloat(distance * 0.4f, distance * 0.6f) / (Math.Abs(manualVel.X) + 0.5f), weakFleshID, wallThickness, wallType: fleshWallID); GenRunners.WalledVeinRunner((int)last.position.X, (int)last.position.Y, strength * genRand.NextFloat(0.9f, 1.1f), Vector2.Normalize(manualVel), genRand.NextFloat(distance * 0.4f, distance * 0.6f) / (Math.Abs(manualVel.X) + 0.5f), weakFleshID, wallThickness, wallType: fleshWallID); last = GenRunners.WalledVeinRunner((int)last.position.X, (int)last.position.Y, strength * genRand.NextFloat(0.9f, 1.1f), new Vector2(0, 1).RotatedByRandom(0.2f, genRand), genRand.NextFloat(distance * 0.4f, distance * 0.6f), weakFleshID, wallThickness, wallType: fleshWallID); //t.ResetToType(TileID.AmethystGemspark); manualVel.X = -manualVel.X; //t = Main.tile[(int)last.position.X, (int)last.position.Y]; GenRunners.WalledVeinRunner((int)last.position.X, (int)last.position.Y, strength * genRand.NextFloat(0.9f, 1.1f), Vector2.Normalize(new Vector2(-manualVel.X, 0.2f)), genRand.NextFloat(distance * 0.4f, distance * 0.6f) * (Math.Abs(manualVel.X) + 0.5f), weakFleshID, wallThickness, wallType: fleshWallID); last = GenRunners.WalledVeinRunner((int)last.position.X, (int)last.position.Y, strength * genRand.NextFloat(0.9f, 1.1f), Vector2.Normalize(manualVel), genRand.NextFloat(distance * 0.4f, distance * 0.6f) / (Math.Abs(manualVel.X) + 0.5f), weakFleshID, wallThickness, wallType: fleshWallID); GenRunners.WalledVeinRunner((int)last.position.X, (int)last.position.Y, strength * genRand.NextFloat(0.9f, 1.1f), Vector2.Normalize(manualVel), genRand.NextFloat(distance * 0.4f, distance * 0.6f) / (Math.Abs(manualVel.X) + 0.5f), weakFleshID, wallThickness, wallType: fleshWallID); last = GenRunners.WalledVeinRunner((int)last.position.X, (int)last.position.Y, strength * genRand.NextFloat(0.9f, 1.1f), new Vector2(0, 1).RotatedByRandom(0.2f, genRand), genRand.NextFloat(distance * 0.4f, distance * 0.6f), weakFleshID, wallThickness, wallType: fleshWallID); //t.ResetToType(TileID.AmethystGemspark); for (int index = 0; index < 10; index++) { //t = Main.tile[(int)last.position.X, (int)last.position.Y]; last = GenRunners.WalledVeinRunner((int)last.position.X, (int)last.position.Y, strength * genRand.NextFloat(0.9f, 1.1f), last.velocity.RotatedByRandom(0.8f, genRand), genRand.NextFloat(distance * 0.2f, distance * 0.3f), weakFleshID, wallThickness, wallType: fleshWallID); if (index < 8) { GenRunners.WalledVeinRunner((int)last.position.X, (int)last.position.Y, strength * genRand.NextFloat(0.9f, 1.1f), last.velocity.RotatedBy(genRand.Next(2) * 2 - 1).RotatedByRandom(0.8f, genRand), genRand.NextFloat(distance * 0.4f, distance * 0.6f), weakFleshID, wallThickness, wallType: fleshWallID); } PolarVec2 vel = new PolarVec2(1, last.velocity.ToRotation()); OriginExtensions.AngularSmoothing(ref vel.Theta, MathHelper.PiOver2, 0.7f); //t.ResetToType(TileID.AmethystGemspark); last = (last.position, (Vector2)vel); } //t = Main.tile[(int)last.position.X, (int)last.position.Y]; //t.ResetToType(TileID.AmethystGemspark); Point caveCenter = HiveCave((int)last.position.X, (int)last.position.Y); Vector2 cavernOpening = last.position - caveCenter.ToVector2(); GenRunners.VeinRunner((int)last.position.X, (int)last.position.Y, strength, cavernOpening.SafeNormalize(Vector2.Zero), cavernOpening.Length()); GenRunners.VeinRunner(startValues.x, startValues.y, strength, startValues.direction, startValues.length); (Vector2 position, Vector2 velocity)[] arms = new (Vector2 position, Vector2 velocity)[4];
public override void PostDraw(SpriteBatch spriteBatch, Color drawColor) { if (!(Main.npc.Any(n => n.active && n.type == ModContent.NPCType <OvergrowBoss>()))) { return; } NPC boss = Main.npc.FirstOrDefault(n => n.active && n.type == ModContent.NPCType <OvergrowBoss>()); Texture2D tex = ModContent.GetTexture("StarlightRiver/NPCs/Boss/OvergrowBoss/Chain"); for (float k = 0; k < 1; k += tex.Height / Vector2.Distance(npc.Center, boss.Center + Vector2.Normalize(npc.Center - boss.Center) * 80)) { if (k > npc.ai[0] / 30f) { Vector2 pos = Vector2.Lerp(npc.Center, boss.Center + Vector2.Normalize(npc.Center - boss.Center) * 80, k); spriteBatch.Draw(tex, pos - Main.screenPosition, tex.Frame(), Lighting.GetColor((int)pos.X / 16, (int)pos.Y / 16), (npc.Center - boss.Center).ToRotation() + 1.58f, tex.Frame().Size() / 2, 1, 0, 0); } } }
public override void Update(GameTime gameTime) { var keyboard = Keyboard.GetState(); _timer.Update(gameTime); _elapsed += gameTime.ElapsedGameTime.TotalSeconds; _playerDirection.X = 0; _playerDirection.Y = 0; if (keyboard.IsKeyDown(Keys.Left) && _playerPosition.Left > 0) { _playerDirection.X = -1; } if (keyboard.IsKeyDown(Keys.Right) && _playerPosition.Right < RenderTarget2D.Width) { _playerDirection.X = 1; } if (keyboard.IsKeyDown(Keys.Up) && _playerPosition.Top > 0) { _playerDirection.Y = -1; } if (keyboard.IsKeyDown(Keys.Down) && _playerPosition.Bottom < RenderTarget2D.Height) { _playerDirection.Y = 1; } _playerPosition.X += (int)Math.Round(_playerDirection.X * _playerSpeed); _playerPosition.Y += (int)Math.Round(_playerDirection.Y * _playerSpeed); _circlePosition.X += (int)Math.Round(_circleDirection.X * _circleSpeed); _circlePosition.Y += (int)Math.Round(_circleDirection.Y * _circleSpeed); var wasChange = false; if (_timer.IsComplete || !RenderTarget2D.Bounds.Contains(_circlePosition)) { wasChange = true; if (_circlePosition.Left <= 0) { _circleDirection = new Vector2((float)_r.NextDouble() * 0.5f, (float)_r.NextDouble() - 0.5f); } else if (_circlePosition.Right >= RenderTarget2D.Width) { _circleDirection = new Vector2((float)_r.NextDouble() * (-0.5f), (float)_r.NextDouble() - 0.5f); } else if (_circlePosition.Top <= 0) { _circleDirection = new Vector2((float)_r.NextDouble() - 0.5f, (float)_r.NextDouble() * 0.5f); } else if (_circlePosition.Bottom >= RenderTarget2D.Height) { _circleDirection = new Vector2((float)_r.NextDouble() - 0.5f, (float)_r.NextDouble() * (-0.5f)); } else { _circleDirection = new Vector2((float)_r.NextDouble() - 0.5f, (float)_r.NextDouble() - 0.5f); } _circleDirection.Normalize(); _timer.Reset(); } _measurements.Add(new ContinuousMeasurements() { Time = gameTime.TotalGameTime, Delta = Vector2.Distance(_circlePosition.Center.ToVector2(), _playerPosition.Center.ToVector2()), DirectionChange = wasChange }); if (!_resultsExported && _elapsed >= _duration) { ExportCSV(); } }
public override void AI() { if (phase == 1) { if (npc.ai[0] == 0f && Main.netMode != NetmodeID.MultiplayerClient) { npc.TargetClosest(true); npc.ai[0] = 1f; } if (Main.player[npc.target].dead || Math.Abs(npc.position.X - Main.player[npc.target].position.X) > 3000f || Math.Abs(npc.position.Y - Main.player[npc.target].position.Y) > 3000f) { npc.TargetClosest(true); if (Main.player[npc.target].dead || Math.Abs(npc.position.X - Main.player[npc.target].position.X) > 3000f || Math.Abs(npc.position.Y - Main.player[npc.target].position.Y) > 3000f) { npc.ai[1] = 3f; } } if (npc.ai[1] != 3f && npc.ai[1] != 2f) { Main.PlaySound(SoundID.Roar, (int)npc.position.X, (int)npc.position.Y, 0, 1f, 0f); npc.ai[1] = 2f; } if (npc.ai[1] == 2f) { npc.rotation += npc.direction * 0.4f; { npc.velocity += Vector2.Normalize(Main.player[npc.target].Center - npc.Center) * new Vector2(.5f, .2f); } npc.velocity *= 0.98f; npc.velocity.X = Utils.Clamp(npc.velocity.X, -15, 15); npc.velocity.Y = Utils.Clamp(npc.velocity.Y, -15, 15); } else if (npc.ai[1] == 3f) { npc.velocity.Y = npc.velocity.Y + 0.1f; if (npc.velocity.Y < 0f) { npc.velocity.Y = npc.velocity.Y * 0.95f; } npc.velocity.X = npc.velocity.X * 0.95f; if (npc.timeLeft > 50) { npc.timeLeft = 50; } } } if (phase == 2) { // timer++; // if (timer >= 2) // { Projectile.NewProjectile(npc.Center.X, npc.Center.Y, 5f * (float)Math.Cos(npc.rotation), 10 * (float)Math.Sin(npc.rotation), ModContent.ProjectileType <MeldMin>(), 300, 3f, Main.myPlayer); // timer = 0; // } if (npc.ai[0] == 0f && Main.netMode != NetmodeID.MultiplayerClient) { npc.TargetClosest(true); npc.ai[0] = 1f; } if (Main.player[npc.target].dead || Math.Abs(npc.position.X - Main.player[npc.target].position.X) > 3000f || Math.Abs(npc.position.Y - Main.player[npc.target].position.Y) > 3000f) { npc.TargetClosest(true); if (Main.player[npc.target].dead || Math.Abs(npc.position.X - Main.player[npc.target].position.X) > 3000f || Math.Abs(npc.position.Y - Main.player[npc.target].position.Y) > 3000f) { npc.ai[1] = 3f; } } if (npc.ai[1] != 3f && npc.ai[1] != 2f) { Main.PlaySound(SoundID.Roar, (int)npc.position.X, (int)npc.position.Y, 0, 1f, 0f); npc.ai[1] = 2f; } if (npc.ai[1] == 2f) { npc.rotation += npc.direction * 0.6f; if (Vector2.Distance(Main.player[npc.target].Center, npc.Center) > 1) { npc.velocity += Vector2.Normalize(Main.player[npc.target].Center - npc.Center) * new Vector2(.5f, .2f); } npc.velocity *= 0.98f; npc.velocity.X = Utils.Clamp(npc.velocity.X, -20, 20); npc.velocity.Y = Utils.Clamp(npc.velocity.Y, -20, 20); } else if (npc.ai[1] == 3f) { npc.velocity.Y = npc.velocity.Y + 0.1f; if (npc.velocity.Y < 0f) { npc.velocity.Y = npc.velocity.Y * 0.95f; } npc.velocity.X = npc.velocity.X * 0.95f; if (npc.timeLeft > 50) { npc.timeLeft = 50; } } } if (phase == 3) { if (npc.ai[0] == 0f && Main.netMode != NetmodeID.MultiplayerClient) { npc.TargetClosest(true); npc.ai[0] = 1f; } if (Main.player[npc.target].dead || Math.Abs(npc.position.X - Main.player[npc.target].position.X) > 3000f || Math.Abs(npc.position.Y - Main.player[npc.target].position.Y) > 3000f) { npc.TargetClosest(true); if (Main.player[npc.target].dead || Math.Abs(npc.position.X - Main.player[npc.target].position.X) > 3000f || Math.Abs(npc.position.Y - Main.player[npc.target].position.Y) > 3000f) { npc.ai[1] = 3f; } } if (npc.ai[1] != 3f && npc.ai[1] != 2f) { Main.PlaySound(SoundID.Roar, (int)npc.position.X, (int)npc.position.Y, 0, 1f, 0f); npc.ai[1] = 2f; } if (npc.ai[1] == 2f) { npc.rotation += npc.direction * 0.2f; if (Vector2.Distance(Main.player[npc.target].Center, npc.Center) > 1) { npc.velocity += Vector2.Normalize(Main.player[npc.target].Center - npc.Center) * new Vector2(.5f, .2f); } npc.velocity *= 0.97f; npc.velocity.X = Utils.Clamp(npc.velocity.X, -20, 20); npc.velocity.Y = Utils.Clamp(npc.velocity.Y, -20, 20); } else if (npc.ai[1] == 3f) { npc.velocity.Y = npc.velocity.Y + 0.1f; if (npc.velocity.Y < 0f) { npc.velocity.Y = npc.velocity.Y * 0.95f; } npc.velocity.X = npc.velocity.X * 0.95f; if (npc.timeLeft > 50) { npc.timeLeft = 50; } } } }
public T2Bullet(Vector2 start, Vector2 end) : base(start, end) { course = Vector2.Normalize(course) * 3; //multiply by speed shoot = shoot2; }
public override void Behavior() { alphaCounter += .04f; bool flag64 = projectile.type == ModContent.ProjectileType <MoonjellySummon>(); Player player = Main.player[projectile.owner]; MyPlayer modPlayer = player.GetSpiritPlayer(); if (flag64) { if (player.dead) { modPlayer.lunazoa = false; } if (modPlayer.lunazoa) { projectile.timeLeft = 2; } } int summonTime; summonTime = (int)(45 / (.33f * projectile.minionSlots)); if (summonTime >= 110) { summonTime = 110; } counter++; if (counter % summonTime == 0) { Vector2 vector2_2 = Vector2.UnitY.RotatedByRandom(1.57079637050629f) * new Vector2(5f, 3f); int p = Projectile.NewProjectile(projectile.Center.X + Main.rand.Next(-50, 50), projectile.Center.Y + Main.rand.Next(-50, 50), vector2_2.X, vector2_2.Y, ModContent.ProjectileType <LunazoaOrbiter>(), projectile.damage, projectile.knockBack, Main.myPlayer, 0.0f, (float)projectile.whoAmI); Main.projectile[p].scale = Main.rand.NextFloat(.4f, 1f); Main.projectile[p].timeLeft = (int)(62 / (.33f * projectile.minionSlots)); counter = 0; } Lighting.AddLight(new Vector2(projectile.Center.X, projectile.Center.Y), 0.075f * 2, 0.231f * 2, 0.255f * 2); projectile.frameCounter++; if (projectile.frameCounter >= 10f) { projectile.frame = (projectile.frame + 1) % Main.projFrames[projectile.type]; projectile.frameCounter = 0; if (projectile.frame >= 10) { projectile.frame = 0; } } projectile.rotation = projectile.velocity.X * 0.025f; trailing = false; projectile.tileCollide = false; float num = projectile.width * 1.1f; for (int i = 0; i < 1000; i++) { Projectile current = Main.projectile[i]; if (i != projectile.whoAmI && current.active && projectile.owner == current.owner && projectile.type == current.type && Math.Abs(projectile.position.X - current.position.X) + Math.Abs(projectile.position.Y - current.position.Y) < num) { if (projectile.position.X < Main.projectile[i].position.X) { projectile.velocity.X -= 0.08f; } else { projectile.velocity.X += 0.08f; } if (projectile.position.Y < Main.projectile[i].position.Y) { projectile.velocity.Y -= 0.08f; } else { projectile.velocity.Y += 0.08f; } } } Vector2 value = projectile.position; float num21 = 920f; bool flag = false; projectile.tileCollide = false; for (int j = 0; j < 200; j++) { NPC nPC = Main.npc[j]; if (nPC.CanBeChasedBy(this, false)) { float num3 = Vector2.Distance(nPC.Center, projectile.Center); if ((num3 < num21 || !flag) && Collision.CanHitLine(projectile.position, projectile.width, projectile.height, nPC.position, nPC.width, nPC.height)) { num21 = num3; value = nPC.Center; flag = true; } } } if (Vector2.Distance(player.Center, projectile.Center) > (flag ? 1000f : 500f)) { projectile.ai[0] = 1f; projectile.netUpdate = true; } if (projectile.ai[0] == 1f) { projectile.tileCollide = false; } if (!Collision.CanHitLine(projectile.Center, 1, 1, player.Center, 1, 1)) { projectile.ai[0] = 1f; } float num4 = 6f; if (projectile.ai[0] == 1f) { num4 = 15f; } Vector2 center = projectile.Center; Vector2 vector = player.Center - center; projectile.ai[1] = 3600f; projectile.netUpdate = true; int num5 = 1; for (int k = 0; k < projectile.whoAmI; k++) { if (Main.projectile[k].active && Main.projectile[k].owner == projectile.owner && Main.projectile[k].type == projectile.type) { num5++; } } vector.X -= 0; vector.Y -= 70f; float num6 = vector.Length(); if (num6 > 200f && num4 < 9f) { num4 = 9f; } if (num6 < 100f && projectile.ai[0] == 1f && !Collision.SolidCollision(projectile.position, projectile.width, projectile.height)) { projectile.ai[0] = 0f; projectile.netUpdate = true; } if (num6 > 2000f) { projectile.Center = player.Center; } if (num6 > 48f) { vector.Normalize(); vector *= num4; float num7 = 10f; projectile.velocity = (projectile.velocity * num7 + vector) / (num7 + 1f); } else { projectile.direction = Main.player[projectile.owner].direction; projectile.velocity *= (float)Math.Pow(0.9, 2.0); } if (projectile.velocity.X > 0f) { projectile.spriteDirection = (projectile.direction = -1); } else if (projectile.velocity.X < 0f) { projectile.spriteDirection = (projectile.direction = 1); } if (projectile.ai[1] > 0f) { projectile.ai[1] += 1f; } if (projectile.ai[1] > 140f) { projectile.ai[1] = 0f; projectile.netUpdate = true; } }
public Vector2 Direction() { return(Vector2.Normalize(MathExtension.AngleToDirection(MathExtension.LineToAngle(this)))); }
/// <summary> /// Process the input for this ship, from the gamepad assigned to it. /// </summary> /// <param name="elapsedTime">The amount of elapsed time, in seconds.</param> /// <para public virtual void ProcessInput(float elapsedTime, bool overlayPresent) { currentGamePadState = GamePad.GetState(playerIndex); if (overlayPresent == false) { if (playing == false) { // trying to join - update the a-button timer if (currentGamePadState.Buttons.A == ButtonState.Pressed) { aButtonTimer += elapsedTime; } else { aButtonTimer = 0f; } // if the timer has exceeded the expected value, join the game if (aButtonTimer > aButtonHeldToPlay) { JoinGame(); } } else { // check if we're trying to leave if (currentGamePadState.Buttons.B == ButtonState.Pressed) { bButtonTimer += elapsedTime; } else { bButtonTimer = 0f; } // if the timer has exceeded the expected value, leave the game if (bButtonTimer > bButtonHeldToLeave) { LeaveGame(); } else if (dead == false) { // // the ship is alive, so process movement and firing // // calculate the current forward vector Vector2 forward = new Vector2((float)Math.Sin(Rotation), -(float)Math.Cos(Rotation)); Vector2 right = new Vector2(-forward.Y, forward.X); // calculate the current left stick value Vector2 leftStick = currentGamePadState.ThumbSticks.Left; leftStick.Y *= -1f; if (leftStick.LengthSquared() > 0f) { Vector2 wantedForward = Vector2.Normalize(leftStick); float angleDiff = (float)Math.Acos( Vector2.Dot(wantedForward, forward)); float facing = (Vector2.Dot(wantedForward, right) > 0f) ? 1f : -1f; if (angleDiff > 0f) { Rotation += Math.Min(angleDiff, facing * elapsedTime * rotationRadiansPerSecond); } // add velocity Velocity += leftStick * (elapsedTime * speed); if (Velocity.Length() > velocityLengthMaximum) { Velocity = Vector2.Normalize(Velocity) * velocityLengthMaximum; } } // check for firing with the right stick Vector2 rightStick = currentGamePadState.ThumbSticks.Right; rightStick.Y *= -1f; if (rightStick.LengthSquared() > fireThresholdSquared) { weapon.Fire(Vector2.Normalize(rightStick)); } // check for laying mines if ((currentGamePadState.Buttons.B == ButtonState.Pressed) && (lastGamePadState.Buttons.B == ButtonState.Released)) { // fire behind the ship mineWeapon.Fire(-forward); } } } } // update the gamepad state lastGamePadState = currentGamePadState; return; }
public override bool PreAI() { npc.TargetClosest(true); npc.velocity.X = npc.velocity.X * 0.93f; if (npc.velocity.X > -0.1F && npc.velocity.X < 0.1F) { npc.velocity.X = 0; } if (npc.ai[0] == 0) { npc.ai[0] = 500f; } if (npc.ai[2] != 0 && npc.ai[3] != 0) { // Teleport effects: away. Main.PlaySound(2, (int)npc.position.X, (int)npc.position.Y, 8); for (int index1 = 0; index1 < 50; ++index1) { int newDust = Dust.NewDust(new Vector2(npc.position.X, npc.position.Y), npc.width, npc.height, 244, 0.0f, 0.0f, 100, new Color(), 1.5f); Main.dust[newDust].velocity *= 3f; Main.dust[newDust].noGravity = true; } npc.position.X = (npc.ai[2] * 16 - (npc.width / 2) + 8); npc.position.Y = npc.ai[3] * 16f - npc.height; npc.velocity.X = 0.0f; npc.velocity.Y = 0.0f; npc.ai[2] = 0.0f; npc.ai[3] = 0.0f; // Teleport effects: arrived. Main.PlaySound(2, (int)npc.position.X, (int)npc.position.Y, 8); for (int index1 = 0; index1 < 50; ++index1) { int newDust = Dust.NewDust(new Vector2(npc.position.X, npc.position.Y), npc.width, npc.height, 244, 0.0f, 0.0f, 100, new Color(), 1.5f); Main.dust[newDust].velocity *= 3f; Main.dust[newDust].noGravity = true; } } ++npc.ai[0]; if (npc.ai[0] == 100 || npc.ai[0] == 200 || npc.ai[0] == 300) { npc.ai[1] = 30f; npc.netUpdate = true; } bool teleport = false; // Teleport if (npc.ai[0] >= 500 && Main.netMode != 1) { teleport = true; } if (teleport) { Teleport(); } if (npc.ai[1] > 0) { --npc.ai[1]; if (npc.ai[1] == 15) { Main.PlaySound(2, (int)npc.position.X, (int)npc.position.Y, 8); if (Main.netMode != 1) { Vector2 direction = Main.player[npc.target].Center - npc.Center; direction.Normalize(); direction.X *= 14f; direction.Y *= 14f; int amountOfProjectiles = Main.rand.Next(1, 2); for (int i = 0; i < amountOfProjectiles; ++i) { float A = (float)Main.rand.Next(-50, 50) * 0.02f; float B = (float)Main.rand.Next(-50, 50) * 0.02f; Projectile.NewProjectile(npc.Center.X, npc.Center.Y, direction.X + A, direction.Y + B, mod.ProjectileType("SunBlast"), npc.damage / 3 * 2, 1, Main.myPlayer, 0, 0); } } } } if (Main.rand.Next(3) == 0) { return(false); } Dust dust = Main.dust[Dust.NewDust(new Vector2(npc.position.X, npc.position.Y + 2f), npc.width, npc.height, 244, npc.velocity.X * 0.2f, npc.velocity.Y * 0.2f, 100, new Color(), 0.9f)]; dust.noGravity = true; dust.velocity.X = dust.velocity.X * 0.3f; dust.velocity.Y = (dust.velocity.Y * 0.2f) - 1; return(false); }
/// <summary> /// Initializes a polygon with the specified vertices /// </summary> /// <param name="vertices">Vertices</param> /// <exception cref="ArgumentNullException">If vertices is null</exception> public Polygon2(Vector2[] vertices) { if (vertices == null) { throw new ArgumentNullException(nameof(vertices)); } Vertices = vertices; Normals = new List <Vector2>(); Vector2 tmp; for (int i = 1; i < vertices.Length; i++) { tmp = Math2.MakeStandardNormal(Vector2.Normalize(Math2.Perpendicular(vertices[i] - vertices[i - 1]))); if (!Normals.Contains(tmp)) { Normals.Add(tmp); } } tmp = Math2.MakeStandardNormal(Vector2.Normalize(Math2.Perpendicular(vertices[0] - vertices[vertices.Length - 1]))); if (!Normals.Contains(tmp)) { Normals.Add(tmp); } var min = new Vector2(vertices[0].X, vertices[0].Y); var max = new Vector2(min.X, min.Y); for (int i = 1; i < vertices.Length; i++) { min.X = Math.Min(min.X, vertices[i].X); min.Y = Math.Min(min.Y, vertices[i].Y); max.X = Math.Max(max.X, vertices[i].X); max.Y = Math.Max(max.Y, vertices[i].Y); } AABB = new Rect2(min, max); Center = new Vector2(0, 0); foreach (var vert in Vertices) { Center += vert; } Center *= (1.0f / Vertices.Length); // Find longest axis float longestAxisLenSq = -1; for (int i = 1; i < vertices.Length; i++) { var vec = vertices[i] - vertices[i - 1]; longestAxisLenSq = Math.Max(longestAxisLenSq, vec.LengthSquared()); } longestAxisLenSq = Math.Max(longestAxisLenSq, (vertices[0] - vertices[vertices.Length - 1]).LengthSquared()); LongestAxisLength = (float)Math.Sqrt(longestAxisLenSq); // Area and lines float area = 0; Lines = new Line2[Vertices.Length]; var last = Vertices[Vertices.Length - 1]; for (int i = 0; i < Vertices.Length; i++) { var next = Vertices[i]; Lines[i] = new Line2(last, next); area += Math2.AreaOfTriangle(last, next, Center); last = next; } Area = area; last = Vertices[Vertices.Length - 1]; var centToLast = (last - Center); var angLast = Math.Atan2(centToLast.Y, centToLast.X); var cwCounter = 0; var ccwCounter = 0; var foundDefinitiveResult = false; for (int i = 0; i < Vertices.Length; i++) { var curr = Vertices[i]; var centToCurr = (curr - Center); var angCurr = Math.Atan2(centToCurr.Y, centToCurr.X); var clockwise = angCurr < angLast; if (clockwise) { cwCounter++; } else { ccwCounter++; } Clockwise = clockwise; if (Math.Abs(angLast - angCurr) > Math2.DEFAULT_EPSILON) { foundDefinitiveResult = true; break; } last = curr; centToLast = centToCurr; angLast = angCurr; } if (!foundDefinitiveResult) { Clockwise = cwCounter > ccwCounter; } }
/// <summary> /// Allows the game to run logic such as updating the world, /// checking for collisions, gathering input, and playing audio. /// </summary> /// <param name="gameTime">Provides a snapshot of timing values.</param> protected override void Update(GameTime gameTime) { MouseState currentMouseState = Mouse.GetState(); KeyboardState currentKeyboardState = Keyboard.GetState(); if (currentMouseState.LeftButton == Microsoft.Xna.Framework.Input.ButtonState.Pressed && lastMouseState.LeftButton == Microsoft.Xna.Framework.Input.ButtonState.Released && ball.onGround) //Will be true only if the user is currently clicking, but wasn't on the previous call. { checker1checked = false; checker2checked = false; Vector2 vector = new Vector2(ball.Center.X - currentMouseState.X, ball.Center.Y - currentMouseState.Y); vector.Normalize(); vector *= -35f; ball.velocity = vector; } if (currentMouseState.RightButton == Microsoft.Xna.Framework.Input.ButtonState.Pressed) { ball.location = new Vector2(Cursor.Position.X - ball.radius, Cursor.Position.Y - ball.radius); ball.velocity = Vector2.Zero; } for (int i = 0; i < 2; i++) { if (doCirclesOverlap(ball.Center.X, ball.Center.Y, ball.radius, kosar[i].Center.X, kosar[i].Center.Y, kosar[i].radius)) { float fDistance = (float)Math.Sqrt((ball.Center.X - kosar[i].Center.X) * (ball.Center.X - kosar[i].Center.X) + (ball.Center.Y - kosar[i].Center.Y) * (ball.Center.Y - kosar[i].Center.Y)); float fOverlap = 0.5f * (fDistance - ball.radius - kosar[i].radius); //static ball.location.X -= fOverlap * (ball.Center.X - kosar[i].Center.X) / fDistance; ball.location.Y -= fOverlap * (ball.Center.Y - kosar[i].Center.Y) / fDistance; //dynamic fDistance = (float)Math.Sqrt((ball.Center.X - kosar[i].Center.X) * (ball.Center.X - kosar[i].Center.X) + (ball.Center.Y - kosar[i].Center.Y) * (ball.Center.Y - kosar[i].Center.Y)); float nx = (kosar[i].Center.X - ball.Center.X) / fDistance; float ny = (kosar[i].Center.Y - ball.Center.Y) / fDistance; float tx = -ny; float ty = nx; float dpTan1 = ball.velocity.X * tx + ball.velocity.Y * ty; float dpNorm1 = ball.velocity.X * nx + ball.velocity.Y * ny; float dpNorm2 = kosar[i].velocity.X * nx + kosar[i].velocity.Y * ny; float m1 = (dpNorm1 * (ball.mass - kosar[i].mass) + 2.0f * kosar[i].mass * dpNorm2) / (ball.mass + kosar[i].mass); ball.velocity.X = tx * dpTan1 + nx * m1 * 0.75f; ball.velocity.Y = ty * dpTan1 + ny * m1 * 0.75f; } } ball.update(); if (!checker1checked) { if (new Rectangle(checker1.X, checker1.Y, checker1.Width, checker1.Height).Contains(new Point((int)ball.Center.X, (int)ball.Center.Y))) { if (!checker2checked) { checker1checked = true; } } } if (!checker2checked) { if (new Rectangle(checker2.X, checker2.Y, checker2.Width, checker2.Height).Contains(new Point((int)ball.Center.X, (int)ball.Center.Y))) { checker2checked = true; if (checker1checked) { pts++; checker1checked = false; } } } lastMouseState = currentMouseState; base.Update(gameTime); }
private void FixedUpdate() { #region Look Settings - FixedUpdate #endregion #region Movement Settings - FixedUpdate bool wasWalking = !isSprinting; if (useStamina) { if (backgroundStamina > 0) { if (!isCrouching) { isSprinting = Input.GetKey(KeyCode.LeftShift); } } if (isSprinting == true && backgroundStamina > 0) { backgroundStamina -= staminaDepletionMultiplier; } else if (backgroundStamina < Stamina && !Input.GetKey(KeyCode.LeftShift)) { backgroundStamina += staminaDepletionMultiplier / 2; } } else { isSprinting = Input.GetKey(KeyCode.LeftShift); } float inrSprintSpeed; inrSprintSpeed = sprintSpeed; speed = walkByDefault ? isCrouching ? walkSpeed : (isSprinting ? inrSprintSpeed : walkSpeed) : (isSprinting ? walkSpeed : inrSprintSpeed); Ray ray = new Ray(transform.position, -transform.up); if (IsGrounded || fps_Rigidbody.velocity.y < 0.1) { RaycastHit[] hits = Physics.RaycastAll(ray, capsule.height * jumpRayLength); float nearest = float.PositiveInfinity; IsGrounded = false; for (int i = 0; i < hits.Length; i++) { if (!hits[i].collider.isTrigger && hits[i].distance < nearest) { IsGrounded = true; nearest = hits[i].distance; } } } float horizontalInput = Input.GetAxis("Horizontal"); float verticalInput = Input.GetAxis("Vertical"); inputXY = new Vector2(horizontalInput, verticalInput); if (inputXY.magnitude > 1) { inputXY.Normalize(); } Vector3 dMove = transform.forward * inputXY.y * speed + transform.right * inputXY.x * walkSpeed; float yv = fps_Rigidbody.velocity.y; bool didJump = canHoldJump?Input.GetButton("Jump"): Input.GetButtonDown("Jump"); if (IsGrounded && didJump && jumpPower > 0) { yv += jumpPower; IsGrounded = false; didJump = false; } if (playerCanMove) { fps_Rigidbody.velocity = dMove + Vector3.up * yv; } else { fps_Rigidbody.velocity = Vector3.zero; } if (dMove.magnitude > 0 || !IsGrounded) { GetComponent <Collider>().material = advanced.zeroFrictionMaterial; } else { GetComponent <Collider>().material = advanced.highFrictionMaterial; } fps_Rigidbody.AddForce(Physics.gravity * (advanced.gravityMultiplier - 1)); if (fOVKick.useFOVKick && wasWalking == isSprinting && fps_Rigidbody.velocity.magnitude > 0.1f && !isCrouching) { StopAllCoroutines(); StartCoroutine(wasWalking ? FOVKickOut() : FOVKickIn()); } if (useCrouch && _crouchModifiers.CrouchInputAxis != string.Empty) { if (Input.GetButton(_crouchModifiers.CrouchInputAxis)) { if (isCrouching == false) { capsule.height /= 2; walkSpeed = _crouchModifiers.walkSpeedWhileCrouching; sprintSpeed = _crouchModifiers.sprintSpeedWhileCrouching; jumpPower = _crouchModifiers.jumpPowerWhileCrouching; isCrouching = true; } } else if (isCrouching == true) { capsule.height *= 2; if (!_crouchModifiers.useExternalModifier) { walkSpeed = _crouchModifiers.defaultWalkSpeed; sprintSpeed = _crouchModifiers.defaultSprintSpeed; jumpPower = _crouchModifiers.defaultJumpPower; } else { walkSpeed = _crouchModifiers.walkSpeed_External; sprintSpeed = _crouchModifiers.sprintSpeed_External; jumpPower = _crouchModifiers.jumpPower_External; } isCrouching = false; } } #endregion #region BETA_SETTINGS - FixedUpdate #endregion #region Headbobbing Settings - FixedUpdate float yPos = 0; float xPos = 0; float zTilt = 0; float xTilt = 0; float bobSwayFactor; float bobFactor; float strideLangthen; float flatVel; if (useHeadbob == true || dynamicFootstep.useDynamicFootStepProcess == true) { Vector3 vel = (fps_Rigidbody.position - previousPosition) / Time.deltaTime; Vector3 velChange = vel - previousVelocity; previousPosition = fps_Rigidbody.position; previousVelocity = vel; springVelocity -= velChange.y; springVelocity -= springPosition * springElastic; springVelocity *= springDampen; springPosition += springVelocity * Time.deltaTime; springPosition = Mathf.Clamp(springPosition, -0.3f, 0.3f); if (Mathf.Abs(springVelocity) < springVelocityThreshold && Mathf.Abs(springPosition) < springPositionThreshold) { springPosition = 0; springVelocity = 0; } flatVel = new Vector3(vel.x, 0.0f, vel.z).magnitude; //old method = strideLangthen = 1 + (flatVel * (bobStrideSpeedLength/10); strideLangthen = 1 + (flatVel * ((headbobFrequency * 2) / 10)); headbobCycle += (flatVel / strideLangthen) * (Time.deltaTime / headbobFrequency); bobFactor = Mathf.Sin(headbobCycle * Mathf.PI * 2); bobSwayFactor = Mathf.Sin(Mathf.PI * (2 * headbobCycle + 0.5f)); bobFactor = 1 - (bobFactor * 0.5f + 1); bobFactor *= bobFactor; yPos = 0; xPos = 0; zTilt = 0; if (useJumdLandMovement) { xTilt = -springPosition * landAngle; } else { xTilt = -springPosition; } if (IsGrounded) { if (new Vector3(vel.x, 0.0f, vel.z).magnitude < 0.1f) { headbobFade = Mathf.MoveTowards(headbobFade, 0.0f, Time.deltaTime); } else { headbobFade = Mathf.MoveTowards(headbobFade, 1.0f, Time.deltaTime); } float speedHeightFactor = 1 + (flatVel * (headbobSpeedMultiplier / 10)); xPos = -(headbobSideMovement / 10) * bobSwayFactor; yPos = springPosition * (jumpAngle / 10) + bobFactor * (headbobHeight / 10) * headbobFade * speedHeightFactor; zTilt = bobSwayFactor * (headbobSwayAngle / 10) * headbobFade; } } if (useHeadbob == true) { head.localPosition = originalLocalPosition + new Vector3(xPos, yPos, 0); head.localRotation = Quaternion.Euler(xTilt, 0, zTilt); //gunBobPassThrough_POS = new Vector3(xPos, yPos, 0); Left over from proprietary/external gun control. Left in place for posable future use. //gunBobPassThrough_QUA = Quaternion.Euler(xTilt, 0, zTilt); Left over from proprietary/external gun control. Left in place for posable future use. } if (dynamicFootstep.useDynamicFootStepProcess) { Vector3 dwn = Vector3.down; RaycastHit hit = new RaycastHit(); if (Physics.Raycast(transform.position, dwn, out hit)) { dynamicFootstep.qikAC = (hit.collider.sharedMaterial == dynamicFootstep._Wood) ? dynamicFootstep._woodFootsteps : ((hit.collider.sharedMaterial == dynamicFootstep._Grass) ? dynamicFootstep._GrassFootsteps : ((hit.collider.sharedMaterial == dynamicFootstep._metalAndGlass) ? dynamicFootstep._metalAndGlassFootsteps : ((hit.collider.sharedMaterial == dynamicFootstep._rockAndConcrete) ? dynamicFootstep._rockAndConcreteFootsteps : ((hit.collider.sharedMaterial == dynamicFootstep._dirtAndGravle) ? dynamicFootstep._dirtAndGravelFootsteps : ((hit.collider.sharedMaterial == dynamicFootstep._Mud)? dynamicFootstep._MudFootsteps : ((hit.collider.sharedMaterial == dynamicFootstep._CustomMaterial)? dynamicFootstep._CustomMaterialFoorsteps : footStepSounds)))))); if (IsGrounded) { if (!previousGrounded) { if (_useFootStepSounds) { audioSource.PlayOneShot(dynamicFootstep.qikAC[Random.Range(0, dynamicFootstep.qikAC.Length)], Volume / 10); } nextStepTime = headbobCycle + 0.5f; } else { if (headbobCycle > nextStepTime) { nextStepTime = headbobCycle + 0.5f; if (_useFootStepSounds) { audioSource.PlayOneShot(dynamicFootstep.qikAC[Random.Range(0, dynamicFootstep.qikAC.Length)], Volume / 10); } } } previousGrounded = true; } else { if (previousGrounded) { if (_useFootStepSounds) { audioSource.PlayOneShot(dynamicFootstep.qikAC[Random.Range(0, dynamicFootstep.qikAC.Length)], Volume / 10); } } previousGrounded = false; } } else { dynamicFootstep.qikAC = footStepSounds; if (IsGrounded) { if (!previousGrounded) { if (_useFootStepSounds) { audioSource.PlayOneShot(landSound, Volume / 10); } nextStepTime = headbobCycle + 0.5f; } else { if (headbobCycle > nextStepTime) { nextStepTime = headbobCycle + 0.5f; int n = Random.Range(0, footStepSounds.Length); if (_useFootStepSounds) { audioSource.PlayOneShot(footStepSounds[n], Volume / 10); } footStepSounds[n] = footStepSounds[0]; } } previousGrounded = true; } else { if (previousGrounded) { if (_useFootStepSounds) { audioSource.PlayOneShot(jumpSound, Volume / 10); } } previousGrounded = false; } } } else { if (IsGrounded) { if (!previousGrounded) { if (_useFootStepSounds) { audioSource.PlayOneShot(landSound, Volume / 10); } nextStepTime = headbobCycle + 0.5f; } else { if (headbobCycle > nextStepTime) { nextStepTime = headbobCycle + 0.5f; int n = Random.Range(0, footStepSounds.Length); if (_useFootStepSounds) { audioSource.PlayOneShot(footStepSounds[n], Volume / 10); footStepSounds[n] = footStepSounds[0]; } } } previousGrounded = true; } else { if (previousGrounded) { if (_useFootStepSounds) { audioSource.PlayOneShot(jumpSound, Volume / 10); } } previousGrounded = false; } } #endregion }
/// <summary> /// Calculates the shortest distance from the specified polygon to the specified point, /// and the axis from polygon to pos. /// /// Returns null if pt is contained in the polygon (not strictly). /// </summary> /// <returns>The distance form poly to pt.</returns> /// <param name="poly">The polygon</param> /// <param name="pos">Origin of the polygon</param> /// <param name="rot">Rotation of the polygon</param> /// <param name="pt">Point to check.</param> public static Tuple <Vector2, float> MinDistance(Polygon2 poly, Vector2 pos, Rotation2 rot, Vector2 pt) { /* * Definitions * * For each line in the polygon, find the normal of the line in the direction of outside the polygon. * Call the side of the original line that contains none of the polygon "above the line". The other side is "below the line". * * If the point falls above the line: * Imagine two additional lines that are normal to the line and fall on the start and end, respectively. * For each of those two lines, call the side of the line that contains the original line "below the line". The other side is "above the line" * * If the point is above the line containing the start: * The shortest vector is from the start to the point * * If the point is above the line containing the end: * The shortest vector is from the end to the point * * Otherwise * The shortest vector is from the line to the point * * If this is not true for ANY of the lines, the polygon does not contain the point. */ var last = Math2.Rotate(poly.Vertices[poly.Vertices.Length - 1], poly.Center, rot) + pos; for (var i = 0; i < poly.Vertices.Length; i++) { var curr = Math2.Rotate(poly.Vertices[i], poly.Center, rot) + pos; var axis = curr - last; Vector2 norm; if (poly.Clockwise) { norm = new Vector2(-axis.Y, axis.X); } else { norm = new Vector2(axis.Y, -axis.X); } norm = Vector2.Normalize(norm); axis = Vector2.Normalize(axis); var lineProjOnNorm = Vector2.Dot(norm, last); var ptProjOnNorm = Vector2.Dot(norm, pt); if (ptProjOnNorm > lineProjOnNorm) { var ptProjOnAxis = Vector2.Dot(axis, pt); var stProjOnAxis = Vector2.Dot(axis, last); if (ptProjOnAxis < stProjOnAxis) { var res = pt - last; return(Tuple.Create(Vector2.Normalize(res), res.Length())); } var enProjOnAxis = Vector2.Dot(axis, curr); if (ptProjOnAxis > enProjOnAxis) { var res = pt - curr; return(Tuple.Create(Vector2.Normalize(res), res.Length())); } var distOnNorm = ptProjOnNorm - lineProjOnNorm; return(Tuple.Create(norm, distOnNorm)); } last = curr; } return(null); }
public override void AI() { Player P = Main.player[npc.target]; #region despawning if (!P.active || P.dead) { npc.TargetClosest(true); if (!P.active || P.dead) { npc.localAI[0]++; } } if (Main.dayTime) { npc.localAI[0]++; } if (npc.localAI[0] >= 300) { npc.active = false; } #endregion #region circle shield and player movement int maxDist = 1000; for (int i = 0; i < 120; i++) { double angle = Main.rand.NextDouble() * 2d * Math.PI; Vector2 offset = new Vector2((float)Math.Sin(angle) * maxDist, (float)Math.Cos(angle) * maxDist);// unit circle yay Dust dust = Main.dust[Dust.NewDust(npc.Center + offset, 0, 0, 6, 0, 0, 100)]; dust.noGravity = true; } for (int i = 0; i < Main.player.Length; i++) { Player player = Main.player[i]; if (player.active && !P.dead && Vector2.Distance(player.Center, npc.Center) > maxDist) { Vector2 toTarget = new Vector2(npc.Center.X - player.Center.X, npc.Center.Y - player.Center.Y); toTarget.Normalize(); float speed = Vector2.Distance(player.Center, npc.Center) > maxDist + 500 ? 1f : 0.5f; player.velocity += toTarget * 0.5f; player.dashDelay = 2; // to stop dashing away player.grappling[0] = -1; // to stop grappling player.grapCount = 0; for (int p = 0; p < Main.projectile.Length; p++) { if (Main.projectile[p].active && Main.projectile[p].owner == player.whoAmI && Main.projectile[p].aiStyle == 7) { Main.projectile[p].Kill(); } } } } int maxdusts = 5; for (int i = 0; i < maxdusts; i++) { float dustDistance = 100; float dustSpeed = 8; Vector2 offset = Vector2.UnitX.RotateRandom(MathHelper.Pi) * dustDistance; Vector2 velocity = -offset.SafeNormalize(-Vector2.UnitY) * dustSpeed; Dust vortex = Dust.NewDustPerfect(new Vector2(npc.Center.X, npc.Center.Y) + offset, 6, velocity, 0, default(Color), 1.5f); vortex.noGravity = true; } #endregion if (npc.localAI[1] == 0) { npc.Center = P.Center - new Vector2(100, 50); npc.localAI[1]++; } npc.ai[0]--; if (!NPC.AnyNPCs(mod.NPCType("AncientWyrmHead"))) { if (npc.ai[0] <= 0) { float Speed = 17f; Main.PlaySound(2, (int)npc.position.X, (int)npc.position.Y, 20); float rotation = (float)Math.Atan2(npc.Center.Y - P.Center.Y, npc.Center.X - P.Center.X); Projectile.NewProjectile(npc.Center.X, npc.Center.Y, (float)((Math.Cos(rotation) * Speed) * -1), (float)((Math.Sin(rotation) * Speed) * -1), mod.ProjectileType("GuardianShot"), 60, 0f, 0); if (npc.life > npc.lifeMax * 0.75f) { npc.ai[0] = Main.rand.Next(30, 120); } else { npc.ai[0] = Main.rand.Next(5, 80); } } } }
/// <summary> /// The AI of the projectile /// </summary> public override void AI() { Vector2 mousePos = Main.MouseWorld; Player player = Main.player[projectile.owner]; #region Set projectile position if (projectile.owner == Main.myPlayer) // Multiplayer support { Vector2 diff = mousePos - player.Center; diff.Normalize(); projectile.position = player.Center + diff * _moveDist; projectile.timeLeft = 2; int dir = projectile.position.X > player.position.X ? 1 : -1; player.ChangeDir(dir); player.heldProj = projectile.whoAmI; player.itemTime = 2; player.itemAnimation = 2; player.itemRotation = (float)Math.Atan2(diff.Y * dir, diff.X * dir); projectile.soundDelay--; #endregion } #region Charging process // Kill the projectile if the player stops channeling if (!player.channel) { projectile.Kill(); } else { if (Main.time % 10 < 1 && !player.CheckMana(player.inventory[player.selectedItem].mana, true)) { projectile.Kill(); } Vector2 offset = mousePos - player.Center; offset.Normalize(); offset *= _moveDist - 20; Vector2 dustPos = player.Center + offset - new Vector2(10, 10); if (_charge < 5) { _charge++; } int chargeFact = _charge / 20; Vector2 dustVelocity = Vector2.UnitX * 18f; dustVelocity = dustVelocity.RotatedBy(projectile.rotation - 1.57f, default(Vector2)); Vector2 spawnPos = projectile.Center + dustVelocity; for (int k = 0; k < chargeFact + 1; k++) { Vector2 spawn = spawnPos + ((float)Main.rand.NextDouble() * 6.28f).ToRotationVector2() * (12f - (chargeFact * 2)); Dust dust = Main.dust[Dust.NewDust(dustPos, 30, 30, 226, projectile.velocity.X / 2f, //this 30, 30 is the dust weight and height 235 is the tail dust projectile.velocity.Y / 2f, 0, new Color(), 1f)]; dust.velocity = Vector2.Normalize(spawnPos - spawn) * 1.5f * (10f - chargeFact * 2f) / 10f; dust.noGravity = true; dust.scale = Main.rand.Next(10, 20) * 0.05f; } } #endregion #region Set laser tail position and dusts if (_charge < 5) { return; } Vector2 start = player.Center; Vector2 unit = (player.Center - mousePos); unit.Normalize(); unit *= -1; for (_moveDist = 95f; _moveDist <= 1600; _moveDist += 5) //this 1600 is the dsitance of the beam { start = player.Center + unit * _moveDist; if (!Collision.CanHit(player.Center, 1, 1, start, 1, 1)) { _moveDist -= 5f; break; } if (projectile.soundDelay <= 0) //this is the proper sound delay for this type of weapon { Main.PlaySound(2, (int)projectile.Center.X, (int)projectile.Center.Y, 15); //this is the sound when the weapon is used cheange 15 for diferent sound projectile.soundDelay = 40; //this is the proper sound delay for this type of weapon } } _targetPos = player.Center + unit * _moveDist; //dust for (int i = 0; i < 2; ++i) { float num1 = projectile.velocity.ToRotation() + (Main.rand.Next(2) == 1 ? -1.0f : 1.0f) * 1.57f; float num2 = (float)(Main.rand.NextDouble() * 0.8f + 1.0f); Vector2 dustVel = new Vector2((float)Math.Cos(num1) * num2, (float)Math.Sin(num1) * num2); Dust dust = Main.dust[Dust.NewDust(_targetPos, 0, 0, 226, dustVel.X, dustVel.Y, 0, new Color(), 1f)]; //this is the head dust Dust dust2 = Main.dust[Dust.NewDust(_targetPos, 0, 0, 226, dustVel.X, dustVel.Y, 0, new Color(), 1f)]; //this is the head dust 2 dust.noGravity = true; dust.scale = 1.2f; } if (_charge == 100) { player.channel = false; } #endregion }
private unsafe void GetRuleBounds(ref BoundingBox request, out BoundingBox ruleBounds) { float y; Vector3 vector2; Vector3 *corners = (Vector3 *)stackalloc byte[(((IntPtr)8) * sizeof(Vector3))]; ruleBounds.Min = new Vector3(float.PositiveInfinity); ruleBounds.Max = new Vector3(float.NegativeInfinity); request.GetCornersUnsafe(corners); if (Vector3.Zero.IsInsideInclusive(ref request.Min, ref request.Max)) { ruleBounds.Min.X = 0f; } else { ruleBounds.Min.X = this.m_planetShape.DistanceToRatio(Vector3.Clamp(Vector3.Zero, request.Min, request.Max).Length()); } Vector3 center = request.Center; vector2.X = (center.X >= 0f) ? request.Max.X : request.Min.X; Vector3 local1 = center; vector2.Y = (local1.Y >= 0f) ? request.Max.Y : request.Min.Y; vector2.Z = (local1.Z >= 0f) ? request.Max.Z : request.Min.Z; ruleBounds.Max.X = this.m_planetShape.DistanceToRatio(vector2.Length()); if (((request.Min.X < 0f) && ((request.Min.Z < 0f) && (request.Max.X > 0f))) && (request.Max.Z > 0f)) { ruleBounds.Min.Z = -1f; ruleBounds.Max.Z = 3f; for (int i = 0; i < 8; i++) { float num4 = (corners + i).Length(); y = corners[i].Y / num4; if (ruleBounds.Min.Y > y) { ruleBounds.Min.Y = y; } if (ruleBounds.Max.Y < y) { ruleBounds.Max.Y = y; } } } else { for (int i = 0; i < 8; i++) { float num6 = (corners + i).Length(); Vector3 *vectorPtr1 = corners + i; vectorPtr1[0] /= num6; y = corners[i].Y; Vector2 vector3 = new Vector2(-corners[i].X, -corners[i].Z); vector3.Normalize(); float num2 = vector3.Y; if (vector3.X > 0f) { num2 = 2f - num2; } if (ruleBounds.Min.Y > y) { ruleBounds.Min.Y = y; } if (ruleBounds.Max.Y < y) { ruleBounds.Max.Y = y; } if (ruleBounds.Min.Z > num2) { ruleBounds.Min.Z = num2; } if (ruleBounds.Max.Z < num2) { ruleBounds.Max.Z = num2; } } } }
public void FixedUpdate() { float speed = runSpeed; // Read input #if CROSS_PLATFORM_INPUT float h = CrossPlatformInput.GetAxis("Horizontal"); float v = CrossPlatformInput.GetAxis("Vertical"); bool jump = CrossPlatformInput.GetButton("Jump"); #else float h = Input.GetAxis("Horizontal"); float v = Input.GetAxis("Vertical"); bool jump = Input.GetButton("Jump"); #endif #if !MOBILE_INPUT // On standalone builds, walk/run speed is modified by a key press. // We select appropriate speed based on whether we're walking by default, and whether the walk/run toggle button is pressed: bool walkOrRun = Input.GetKey(KeyCode.LeftShift); speed = walkByDefault ? (walkOrRun ? runSpeed : walkSpeed) : (walkOrRun ? walkSpeed : runSpeed); // On mobile, it's controlled in analogue fashion by the v input value, and therefore needs no special handling. #endif input = new Vector2(h, v); // normalize input if it exceeds 1 in combined length: if (input.sqrMagnitude > 1) { input.Normalize(); } // Get a vector which is desired move as a world-relative direction, including speeds Vector3 desiredMove = transform.forward * input.y * speed + transform.right * input.x * strafeSpeed; // preserving current y velocity (for falling, gravity) float yv = GetComponent <Rigidbody>().velocity.y; // add jump power if (grounded && jump) { yv += jumpPower; grounded = false; } // Set the rigidbody's velocity according to the ground angle and desired move GetComponent <Rigidbody>().velocity = desiredMove + Vector3.up * yv; // Use low/high friction depending on whether we're moving or not if (desiredMove.magnitude > 0 || !grounded) { GetComponent <Collider>().material = advanced.zeroFrictionMaterial; } else { GetComponent <Collider>().material = advanced.highFrictionMaterial; } // Ground Check: // Create a ray that points down from the centre of the character. Ray ray = new Ray(transform.position, -transform.up); // Raycast slightly further than the capsule (as determined by jumpRayLength) RaycastHit[] hits = Physics.RaycastAll(ray, capsule.height * jumpRayLength); System.Array.Sort(hits, rayHitComparer); if (grounded || GetComponent <Rigidbody>().velocity.y < jumpPower * .5f) { // Default value if nothing is detected: grounded = false; // Check every collider hit by the ray for (int i = 0; i < hits.Length; i++) { // Check it's not a trigger if (!hits[i].collider.isTrigger) { // The character is grounded, and we store the ground angle (calculated from the normal) grounded = true; // stick to surface - helps character stick to ground - specially when running down slopes //if (rigidbody.velocity.y <= 0) { GetComponent <Rigidbody>().position = Vector3.MoveTowards(GetComponent <Rigidbody>().position, hits[i].point + Vector3.up * capsule.height * .5f, Time.deltaTime * advanced.groundStickyEffect); //} GetComponent <Rigidbody>().velocity = new Vector3(GetComponent <Rigidbody>().velocity.x, 0, GetComponent <Rigidbody>().velocity.z); break; } } } Debug.DrawRay(ray.origin, ray.direction * capsule.height * jumpRayLength, grounded ? Color.green : Color.red); // add extra gravity GetComponent <Rigidbody>().AddForce(Physics.gravity * (advanced.gravityMultiplier - 1)); }