public Busje() { Model = Content.Load<Model>(@"Aflevering\Models\BusjeMetJuisteOorsprongWielen"); //Position = new Vector3(x, y, z); BoundingBoxScale = new Vector3(2.5f, 2.5f, 5.5f); BoundingBoxOffset = new Vector3(-2.5f, 1.5f, 4.0f); Scale = new Vector3(0.20f, 0.20f, 0.20f); RotateY = 0.0f; //using physics class to calculate physics for this model Physics = new Physics(); //for (int i = 1; i < 5; i++) //{ // for (int l = 1; l < 3; l++) // { // Console.WriteLine("<gameobject>"); // Console.WriteLine(" <class>ParkBench</class>"); // Console.WriteLine(" <uid>parkBench</uid>"); // Console.WriteLine(" <position>-13,0.4," + (-240 + i * -20) + "</position>"); // Console.WriteLine(" <rotationY>0</rotationY>"); // Console.WriteLine(" <rotationZ>0</rotationZ>"); // Console.WriteLine(" <collission>none</collission>"); // Console.WriteLine(" <firemouseover>false</firemouseover>"); // Console.WriteLine(" <firemouseclick>false</firemouseclick>"); // Console.WriteLine("</gameobject>"); // } //} }
public StateTypeSet(StateSystem statesystem, String label, TextSection textsection) : base(statesystem, label, textsection) { m_statetype = textsection.GetAttribute<StateType>("statetype", StateType.Unchanged); m_movetype = textsection.GetAttribute<MoveType>("movetype", MoveType.Unchanged); m_physics = textsection.GetAttribute<Physics>("Physics", Physics.Unchanged); }
/// <summary> /// Creates a new GameModel object. /// </summary> /// <param name="factory">The assigned ShortLifespanObjectFactory to create new WorldObjects.</param> /// <param name="physics">The assigned Physics to calculate new positions.</param> /// <param name="players">An array of all participating players.</param> /// <param name="world">The assigned World.</param> public GameModel(ShortLifespanObjectFactory factory, Physics physics, List<Player> players, World world) { this.factory = factory; this.physics = physics; this.players = players; this.world = world; }
public Cursor(EntityState es, Town t, XmlParser xp) : base(es, "Cursor") { _town = t; //Current data path is GameState->Town->Cursor var path = es.Name + "->" + _town.Name + "->" + Name; Body = new Body(this, "Body"); AddComponent(Body); Physics = new Physics(this, "Physics"); AddComponent(Physics); ImageRender = new ImageRender(this, "ImageRender"); AddComponent(ImageRender); _aimleftkey = new DoubleInput(this, "AimLeftKey", Keys.A, Buttons.DPadLeft, PlayerIndex.One); AddComponent(_aimleftkey); _aimrightkey = new DoubleInput(this, "AimRightKeys", Keys.D, Buttons.DPadRight, PlayerIndex.One); AddComponent(_aimrightkey); _quickaimkey = new DoubleInput(this, "QuickAimKey", Keys.LeftShift, Buttons.RightShoulder, PlayerIndex.One); AddComponent(_quickaimkey); ParseXml(xp, path); ImageRender.Origin = new Vector2(ImageRender.Texture.Width / 2f, ImageRender.Texture.Height / 2f); Body.Position = _town.Body.Position + (_town.TileRender.Origin - Vector2.UnitY * 40 - ImageRender.Origin) * ImageRender.Scale; }
public override void Initialize() { camera = new Camera2D(Game); physics = new Physics(Game, camera); CreateBodies(); }
public new bool OnCollision(Fixture f1, Fixture f2, Physics.Dynamics.Contacts.Contact c) { // Check if f2 is player if (f2 == SolitudeScreen.ship.Player.PlayerFixture) { SolitudeScreen.ship.Player.oxygen -= Settings.maulerDamage; } return true; }
private Physics CreatePhysics(ErrorCallback errorCallback = null) { if (Physics.Instantiated) Assert.Fail("Physics is still created"); var foundation = new Foundation(errorCallback); var physics = new Physics(foundation, checkRuntimeFiles: true); return physics; }
public Text(EntityState es, string name) : base(es, name) { Body = new Body(this, "Body"); AddComponent(Body); Physics = new Physics(this, "Physics"); AddComponent(Physics); TextRender = new TextRender(this, "TextRender"); AddComponent(TextRender); }
public bool OnCollision(Fixture f1, Fixture f2, Physics.Dynamics.Contacts.Contact c) { if (f2 == SolitudeScreen.ship.Player.PlayerFixture) { if (DateTime.Now - lastCollided >= TimeSpan.FromSeconds(1)) { lastCollided = DateTime.Now; SolitudeScreen.ship.Player.oxygen -= 50; } } return true; }
public Image(EntityState es, string name, Texture2D texture, Vector2 position) : base(es, name) { Body = new Body(this, "Body", position); AddComponent(Body); Physics = new Physics(this, "Physics"); AddComponent(Physics); ImageBaseRender = new ImageRender(this, "ImageRender", texture); AddComponent(ImageBaseRender); }
public Text(EntityState es, string name, SpriteFont font, string text, Vector2 position) : base(es, name) { Body = new Body(this, "Body", position); AddComponent(Body); Physics = new Physics(this, "Physics"); AddComponent(Physics); TextRender = new TextRender(this, "TextRender", font, text); AddComponent(TextRender); }
public Image(EntityState es, string name) : base(es, name) { Body = new Body(this, "Body"); AddComponent(Body); Physics = new Physics(this, "Physics"); AddComponent(Physics); ImageBaseRender = new ImageRender(this, "ImageRender"); AddComponent(ImageBaseRender); }
public void PlaceToScene(Vector3 position, Physics.Newton.World world) { this.world = world; Body = new Box(position - box_size / 2, position + box_size / 2, material, world); Body.physic_body.SetMass(mass, mass*Body.inertia); // global gravity Body.physic_body.SetForceAndTorqueEvent += delegate(Physics.Newton.Body body, float timestep, int threadIndex) { body.AddForce(gravity * mass); }; }
public static Car createCar(Pose pose, Physics ph) { // рожаем машину Car car; var p = new CarParams(); p.InitDefault(); p.h = 2.5f; p.h_base = 2f; car = new Car(p, 0); car.Create(ph, pose); return car; }
public PlayerBehavior(GameObject p_object, ObjectType t) { this.lavaDamageTimer.Timer = -1; this.thisObject = p_object; this.currentPhysics = Physics.None; try { if (GameEngine.Game.GetPlayerStats().IsUnderwater) { this.SetPhysics(Physics.InWater); } else { this.SetPhysics(Physics.Normal); } } catch { this.SetPhysics(Physics.Normal); } switch (t) { case ObjectType.Fox: this.canDuck = true; return; case ObjectType.Human: this.canDuck = true; return; case ObjectType.Lizard: this.canDuck = true; return; case ObjectType.Mouse: this.canDuck = false; return; case ObjectType.Piranha: this.canDuck = false; return; case ObjectType.Tiger: this.canDuck = false; return; case ObjectType.Hawk: this.canDuck = false; return; } }
/// <summary> /// Creates a new plot vector from a particular particle. /// </summary> /// <param name="SeedParticle">The particle to extract the data from</param> public PlotVector(Physics.Particle SeedParticle) { this.Position = SeedParticle.GetActualPosition(); this.Radius = SeedParticle.Radius; int CurrentLayer = 0; Physics.Particle ParentParticle = SeedParticle.ParentParticle; while (ParentParticle != null) { CurrentLayer++; ParentParticle = ParentParticle.ParentParticle; } this.Layer = CurrentLayer; }
public void CreateAndCleanlyDisposeOfFoundationWithPhysics() { var error = new ExceptionErrorCallback() { BadMessages = new[] { "" } }; using (var foundation = new Foundation(error)) { using (var physics = new Physics(foundation)) { } } }
public void CreateAndDisposePhysicsInstance() { using (var foundation = new Foundation(new ConsoleErrorCallback())) { Physics physics; using (physics = new Physics(foundation)) { GC.Collect(); Assert.IsFalse(physics.Disposed); } Assert.IsTrue(physics.Disposed); } }
public Soldier(EntityState es, string name, XmlParser xp) : base(es, name) { Name = name + ID; Body = new Body(this, "Body"); AddComponent(Body); Physics = new Physics(this, "Physics"); AddComponent(Physics); Animation = new Animation(this, "Animation"); Animation.Start(); AddComponent(Animation); Collision = new Collision(this, "Collision"); AddComponent(Collision); Health = new Health(this, "Health"); Health.DiedEvent += OnDeath; AddComponent(Health); _attacktimer = new Timer(this, "AttackTimer"); _attacktimer.LastEvent += OnAttackTimer; AddComponent(_attacktimer); _attacksound = new Sound(this, "AttackSound"); AddComponent(_attacksound); _hitsound = new Sound(this, "HitSound"); AddComponent(_hitsound); _ge = new GibEmitter(this, "GibEmitter"); AddComponent(_ge); string path = es.Name + "->" + "Soldier"; ParseXml(xp, path); Animation.Flip = (_rand.RandomBool()) ? SpriteEffects.None : SpriteEffects.FlipHorizontally; Physics.Velocity.X = (Animation.Flip == SpriteEffects.None) ? -_speed : _speed; Body.Position.X = (Animation.Flip == SpriteEffects.None) ? es.GameRef.Viewport.Right + 10 : -10; Body.Position.Y = 520 - _rand.Next(-10, 10); //TODO: Set origin //TODO: Set Health.DiedEvent to emit blood particles and Destroy }
static int _CreatePhysics(IntPtr L) { int count = LuaDLL.lua_gettop(L); if (count == 0) { Physics obj = new Physics(); LuaScriptMgr.PushObject(L, obj); return 1; } else { LuaDLL.luaL_error(L, "invalid arguments to method: Physics.New"); } return 0; }
private void Form1_Load(object sender, EventArgs e) { //инциализируем отрисовку и физику gh = new GraphicsHelper(pictureBox1); ghover = new GraphicsHelper(pictureBoxOverlay); ph = new Physics(); Vec2 target = new Vec2(75F, 6f); //Координаты конечной точки // рожаем машину var p = new CarParams(); p.InitDefault(); //Задает машине параметры по умолчанию p.h = 2.5f; //Поправляем форму машинки p.h_base = 2f; var ps = new Pose() { xc = 5, yc = 15, angle_rad = 30 * Helper.angle_to_rad }; //Задаем начальное положение машины car = new Car(p, 0); car.Create(ph, ps); //создание агента и среды carAgent = new LICStreeAgent(ps,target); pictureBox2.Image = new Bitmap(pictureBox2.Width, pictureBox2.Height); env = new Environment(ph, car, target,pictureBox2); //создание объектов среды //ВАЖНО!!! -- в каком порядке объекты создаются, в таком они и отрисовываются, поэтому в первую очередь создаются объекты заднего плана. //занятно...-- НЕсамообучающийся по картинке агент ооочень туго переваривает динамические препятствия. Хотя, всё же, переваривает. env.CreateRectZone(new Pose { xc = 30f, yc = 23f, angle_rad = 45 * k_PI }, new Vec2(15f, 25f), 2f); env.CreateRectZone(new Pose { xc = 70f, yc = 20f, angle_rad = 45 * k_PI }, new Vec2(10f, 5f), 3f); env.CreateWall( new Pose { xc = 25f, yc = 17f, angle_rad = 20 * k_PI },new Vec2(2f, 10f)); env.CreateWall(new Pose { xc = 20f, yc = 35f, angle_rad = 35 * k_PI }, new Vec2(10f, 10f)); env.CreateWall(new Pose { xc = 40f, yc = 10f, angle_rad = 35 * k_PI }, new Vec2(40f, 1f)); env.CreateWall( new Pose { xc = 55f, yc = 30f, angle_rad = 100 * k_PI },new Vec2(2f, 10f)); env.CreateWall(new Pose { xc = 65f, yc = 45f, angle_rad = 0 * k_PI }, new Vec2(15f, 15f)); env.CreateWall(new Pose { xc = 25f, yc = 25f, angle_rad = -195 * k_PI }, new Vec2(20f, 1f)); env.CreateWall(new Pose { xc = 50f, yc = 20f, angle_rad = 105 * k_PI }, new Vec2(2f, 7f)); env.CreateWall(new Pose { xc = 58f, yc = 18f, angle_rad = 45 * k_PI }, new Vec2(10f, 5f)); env.CreateWall(new Pose { xc = pictureBox1.Width/20f, yc = pictureBox1.Height/10f, angle_rad = 90 * k_PI }, new Vec2(1f, 10000f)); env.CreateWall(new Pose { xc = pictureBox1.Width / 20f, yc = 0/10f, angle_rad = 90 * k_PI }, new Vec2(1f, 10000f)); env.CreateWall(new Pose { xc = pictureBox1.Width / 10f, yc = pictureBox1.Height / 20f, angle_rad = 0 * k_PI }, new Vec2(1f, 10000f)); env.CreateWall(new Pose { xc = 0/10f, yc = pictureBox1.Height / 20f, angle_rad = 0 * k_PI }, new Vec2(1f, 10000f)); //env.CreateCircle(new Pose { xc = 25f, yc = 20f, angle_rad = -10 * k_PI }, 3, 10); //env.CreateFire(new Pose { xc = 0f, yc = 0f, angle_rad = -10 * k_PI },5); }
public bool OnCollision(Fixture f1, Fixture f2, Physics.Dynamics.Contacts.Contact c) { // Check if f2 is player if (f2 == SolitudeScreen.ship.Player.PlayerFixture && type != WallType.Smooth) { if (type == WallType.HandHold) //grab on to wall { SolitudeScreen.ship.Player.body.LinearVelocity = Vector2.Zero; SolitudeScreen.ship.Player.body.AngularVelocity = 0f; SolitudeScreen.ship.Player.onWall = true; SolitudeScreen.ship.Player.standingOn = (Wall)this; } else if (SolitudeScreen.ship.Player.hasGloves && type == WallType.Grip) // grab if player has gloves { SolitudeScreen.ship.Player.body.LinearVelocity = Vector2.Zero; SolitudeScreen.ship.Player.body.AngularVelocity = 0f; SolitudeScreen.ship.Player.onWall = true; SolitudeScreen.ship.Player.standingOn = this; } else if (SolitudeScreen.ship.Player.hasBoots && type == WallType.Metal) // grab if player has boots { SolitudeScreen.ship.Player.body.LinearVelocity = Vector2.Zero; SolitudeScreen.ship.Player.body.AngularVelocity = 0f; SolitudeScreen.ship.Player.onWall = true; SolitudeScreen.ship.Player.standingOn = this; } else //otherwise { switch (type) //switch because player info is irrelevant { case WallType.Cold: break; case WallType.Hot: break; case WallType.Spike: break; } } } // Check if f2 is other item (ie block) return true; }
public TestEntity(EntityState es, string name) : base(es, name) { Body = new Body(this, "Body", Vector2.One); AddComponent(Body); Body2 = new Body(this, "Body2", Vector2.One * 2); AddComponent(Body2); Body3 = new Body(this, "Body3", Vector2.One * 3); AddComponent(Body3); Physics = new Physics(this, "Physics"); Physics.Drag = .9f; AddComponent(Physics); Collision = new Collision(this, "Collision"); AddComponent(Collision); }
public Particle(int index, Vector2 position, int ttl, Emitter e) : base(e.Entity.StateRef, e.Name + ".Particle") { Name = Name + ID; Body = new Body(this, "Body", position); AddComponent(Body); TileRender = new TileRender(this, "TileRender", e.Texture, e.TileSize); TileRender.Index = index; AddComponent(TileRender); Physics = new Physics(this, "Physics"); AddComponent(Physics); Emitter = e; TimeToLive = ttl; MaxTimeToLive = TimeToLive; }
public void ThrowsExceptionOnDuplicateInstantiation() { using (var foundation = new Foundation(new ConsoleErrorCallback())) { try { using (var physics = new Physics(foundation)) { using (var physics2 = new Physics(foundation)) { } } Assert.Fail("Creating multiple physics instances should throw an exception"); } catch (PhysicsAlreadyInstantiatedException) { } } }
public void CreateAndDisposeSceneInstance() { using (var foundation = new Foundation()) { using (var physics = new Physics(foundation)) { var sceneDesc = new SceneDesc(); Scene scene; using (scene = physics.CreateScene(sceneDesc)) { GC.Collect(); Assert.IsFalse(scene.Disposed); } Assert.IsFalse(physics.Disposed); Assert.IsTrue(scene.Disposed); } } }
public Helicopter(EntityState es, string name, XmlParser xp) : base(es, name) { Name = name + ID; _xp = xp; Body = new Body(this, "Body"); AddComponent(Body); Physics = new Physics(this, "Physics"); AddComponent(Physics); Animation = new Animation(this, "Animation"); AddComponent(Animation); Collision = new Collision(this, "Collision"); AddComponent(Collision); Health = new Health(this, "Health"); Health.DiedEvent += OnDeath; AddComponent(Health); _ge = new GibEmitter(this, "GibEmitter"); AddComponent(_ge); _explodeanim = new Animation(this, "ExplodeAnim"); _explodeanim.LastFrameEvent += Destroy; AddComponent(_explodeanim); _hitsound = new Sound(this, "HitSound"); AddComponent(_hitsound); string path = es.Name + "->Helicopter"; ParseXml(xp, path); Animation.Flip = (_rand.RandomBool()) ? SpriteEffects.None : SpriteEffects.FlipHorizontally; Physics.Velocity.X = (Animation.Flip == SpriteEffects.None) ? -.4f : .4f; Body.Position.Y = 300 - _rand.Next(-10, 10); Body.Position.X = (Animation.Flip == SpriteEffects.None) ? es.GameRef.Viewport.Right + 10 : -10; }
public Bomb(EntityState es, string name, XmlParser xp) : base(es, name) { string path = es.Name + "->" + "Bomb"; Name = Name + ID; Body = new Body(this, "Body"); AddComponent(Body); Physics = new Physics(this, "Physics"); AddComponent(Physics); Collision = new Collision(this, "Collision"); Collision.CollideEvent += CollisionHandler; AddComponent(Collision); ImageRender = new ImageRender(this, "ImageRender"); AddComponent(ImageRender); _explodeanim = new Animation(this, "ExplodeAnim"); _explodeanim.LastFrameEvent += Destroy; AddComponent(_explodeanim); _explodesound = new Sound(this, "ExplodeSound"); AddComponent(_explodesound); _explosionemitter = new ExplosionEmitter(this); AddComponent(_explosionemitter); _smokeemitter = new SmokeEmitter(this); AddComponent(_smokeemitter); ParseXml(xp, path); //TODO: Hook up Collision.CollideEvent to a handler _explodeanim.Origin = new Vector2(_explodeanim.TileSize.X / 2.0f, _explodeanim.TileSize.Y / 2.0f); ImageRender.Origin = new Vector2(ImageRender.Texture.Width / 2f, ImageRender.Texture.Height / 2f); }
public Car(Physics ph,CarParams p,Pose pose) { this.p = p; car_angle0 = Helper.GetRelAngle(new Vec2(1, 0), forwardVec); body = ph.CreateBox(new Pose { xc = pose.xc, yc = pose.yc }, new Box2DX.Common.Vec2 { X = p.w, Y = p.h }, new BodyBehaviour { isDynamic = true, k = 0.98f * p.mass }); bodyFW1 = ph.CreateBox(new Pose { xc = pose.xc, yc = pose.yc + p.h_base / 2 }, new Box2DX.Common.Vec2 { X = p.w / 10, Y = p.h / 10 }, new BodyBehaviour { isDynamic = true, k = 0.01f * p.mass }); bodyBW1 = ph.CreateBox(new Pose { xc = pose.xc, yc = pose.yc + -p.h_base / 2 }, new Box2DX.Common.Vec2 { X = p.w / 10, Y = p.h / 10 }, new BodyBehaviour { isDynamic = true, k = 0.01f * p.mass }); var jFW1def = new RevoluteJointDef(); jFW1def.Initialize(body, bodyFW1, bodyFW1.GetWorldCenter()); jFW1def.EnableMotor = true; jFW1def.MaxMotorTorque = 1000; jFW1def.EnableLimit = true; jFW1def.LowerAngle = -p.max_steer_angle * Helper.angle_to_rad; jFW1def.UpperAngle = p.max_steer_angle * Helper.angle_to_rad; jFW1 = (RevoluteJoint)ph.world.CreateJoint(jFW1def); var jBW1def = new PrismaticJointDef(); jBW1def.Initialize(body, bodyBW1, bodyBW1.GetWorldCenter(), new Vec2(1, 0)); jBW1def.EnableLimit = true; jBW1def.UpperTranslation = jBW1def.LowerTranslation = 0; jBW1 = (PrismaticJoint)ph.world.CreateJoint(jBW1def); //LidarParams lp = new LidarParams() { dir_deg = 0, d0 = 2.2f, dist = 20, fov_deg = 60, x0 = 0, y0 = 0, num_rays = 20 }; var p1 = new LidarParams(); p1.InitDefault(); p1.d0 = p.h / 2 + 0.2f; InitLidar(p1); body.SetAngle(pose.angle_rad); //rcs = new RCS(this); }
public State(StateSystem statesystem, Int32 number, TextSection textsection, List<StateController> controllers) { if (statesystem == null) throw new ArgumentNullException("statesystem"); if (number < -3) throw new ArgumentOutOfRangeException("State number must be greater then or equal to -3"); if (textsection == null) throw new ArgumentNullException("textsection"); if (controllers == null) throw new ArgumentNullException("controllers"); m_statesystem = statesystem; m_number = number; m_controllers = new ReadOnlyList<StateController>(controllers); m_statetype = textsection.GetAttribute<StateType>("type", StateType.Standing); m_movetype = textsection.GetAttribute<MoveType>("MoveType", MoveType.Idle); m_physics = textsection.GetAttribute<Physics>("Physics", Physics.None); m_animationnumber = textsection.GetAttribute<Evaluation.Expression>("anim", null); m_velocity = textsection.GetAttribute<Evaluation.Expression>("velset", null); m_control = textsection.GetAttribute<Evaluation.Expression>("ctrl", null); m_power = textsection.GetAttribute<Evaluation.Expression>("poweradd", null); m_jugglepoints = textsection.GetAttribute<Evaluation.Expression>("juggle", null); m_faceenemy = textsection.GetAttribute<Evaluation.Expression>("facep2", null); m_hitdefpersist = textsection.GetAttribute<Evaluation.Expression>("hitdefpersist", null); m_movehitpersist = textsection.GetAttribute<Evaluation.Expression>("movehitpersist", null); m_hitcountpersist = textsection.GetAttribute<Evaluation.Expression>("hitcountpersist", null); m_spritepriority = textsection.GetAttribute<Evaluation.Expression>("sprpriority", null); }
// Update is called once per frame void Update() { //check if the unit is selected if (_casterMoveInput.isSelected) { //enable or disable spellcast on keypress if (Input.GetKeyUp(spellHotkey1)) { buttonPressed = 1; Button1Animation.GetComponentInParent <Button>().onClick.Invoke(); } else if (Input.GetKeyUp(spellHotkey2)) { Button2Animation.GetComponentInParent <Button>().onClick.Invoke(); buttonPressed = 2; } else if (Input.GetKeyUp(spellHotkey3)) { Button3Animation.GetComponentInParent <Button>().onClick.Invoke(); buttonPressed = 3; } else if (Input.GetKeyUp(spellHotkey4)) { Button4Animation.GetComponentInParent <Button>().onClick.Invoke(); buttonPressed = 4; } else if (Input.GetKeyUp(spellHotkey5)) { Button5Animation.GetComponentInParent <Button>().onClick.Invoke(); buttonPressed = 5; } else if (Input.GetKeyUp(spellHotkey6)) { toggleMovement(); } } //if the caster has an ability selected if (usingAbility == true) { //if the left mouse button is pressed if (Input.GetButtonUp("Fire1")) { //cast a ray from the main camera to the mouse ray = Camera.main.ScreenPointToRay(Input.mousePosition); RaycastHit hit; if (Physics.Raycast(ray, out hit, 100)) { //if the ray hits an object with the Unit tag if (hit.collider.tag == "UI") { hit = new RaycastHit(); } else if (hit.collider.tag == "Unit") { if (canCast(hit.collider.gameObject.GetComponent <CharacterStatus>(), abilityUsed) != -1) { //cast an ability if (buttonPressed == 1) { copyInfo(Button1Animation); gameObject.GetComponentInParent <CastSpell>().callCast(hit.collider.gameObject.GetComponent <CharacterStatus>(), abilityUsed, 1); } if (buttonPressed == 2) { copyInfo(Button2Animation); gameObject.GetComponentInParent <CastSpell>().callCast(hit.collider.gameObject.GetComponent <CharacterStatus>(), abilityUsed, 2); } if (buttonPressed == 3) { copyInfo(Button3Animation); gameObject.GetComponentInParent <CastSpell>().callCast(hit.collider.gameObject.GetComponent <CharacterStatus>(), abilityUsed, 3); } if (buttonPressed == 4) { copyInfo(Button4Animation); gameObject.GetComponentInParent <CastSpell>().callCast(hit.collider.gameObject.GetComponent <CharacterStatus>(), abilityUsed, 4); } if (buttonPressed == 5) { copyInfo(Button5Animation); gameObject.GetComponentInParent <CastSpell>().callCast(hit.collider.gameObject.GetComponent <CharacterStatus>(), abilityUsed, 5); } } //ability has been cast so de-select it usingAbility = false; abilityUsed = 0; } } } } }
//Check if the boid is heading towards an obstacle; if so, fire rays out in increasing angles to the left, right, //above and below the boid in order to find a path around an obstacle. //If multiple rays find a path, select the one closest to the boid's current velocity. Vector3 AvoidObstacles() { Vector3 avoidVector = Vector3.zero; //return vector //fire a ray in direction of boid's velocity (sqr magnitude of velocity in length; change this?) to see if there is an obstacle in its path. //if there is an obstacle in its path (regardless of whether it is currently avoiding a(nother) obstacle, //find avoid vector which is closest to either current velocity vector or mouse target, depending on if using mouse follow. Vector3 target; float checkDistance; if (ControlInputs.Instance.useMouseFollow) { target = mouseTarget - transform.position; checkDistance = Vector3.Distance(transform.position, mouseTarget); } else { target = rb.velocity; checkDistance = OBSTACLE_CHECK_DISTANCE; } RaycastHit hit; if (Physics.Raycast(transform.position, target, out hit, checkDistance, LAYER_OBSTACLE)) { int raycastTries = 0; float inc = rayIncrement; Vector3 closestVector = Vector3.positiveInfinity; bool foundAvoidVector = false; float minDiff = Mathf.Infinity; while (raycastTries <= MAX_OBSTACLE_RAYCAST_TRIES) { //up Vector3 up = new Vector3(target.x, target.y + inc, target.z - inc); //Debug.DrawRay(transform.position, up, Color.blue); if (!Physics.Raycast(transform.position, up, checkDistance, LAYER_OBSTACLE)) //if this raycast doesn't hit { closestVector = up; minDiff = Vector3.SqrMagnitude(target - up); foundAvoidVector = true; } //right Vector3 right = new Vector3(target.x + inc, target.y, target.z - inc); float rightDiff = Vector3.SqrMagnitude(target - right); //Debug.DrawRay(transform.position, right, Color.blue); if (rightDiff < minDiff && !Physics.Raycast(transform.position, right, checkDistance, LAYER_OBSTACLE)) //if this raycast doesn't hit { closestVector = right; minDiff = rightDiff; foundAvoidVector = true; } //down Vector3 down = new Vector3(target.x, target.y - inc, target.z - inc); float downDiff = Vector3.SqrMagnitude(target - down); //Debug.DrawRay(transform.position, down, Color.blue); if (downDiff < minDiff && !Physics.Raycast(transform.position, down, checkDistance, LAYER_OBSTACLE)) //if this raycast doesn't hit { closestVector = down; minDiff = downDiff; foundAvoidVector = true; } //left Vector3 left = new Vector3(target.x - inc, target.y, target.z - inc); //Debug.DrawRay(transform.position, left, Color.blue); if (Vector3.SqrMagnitude(target - left) < minDiff && !Physics.Raycast(transform.position, left, checkDistance, LAYER_OBSTACLE)) //if this raycast doesn't hit { closestVector = left; foundAvoidVector = true; } //if we found a way/ways around obstacle on this loop, return closestVector if (foundAvoidVector) { Debug.DrawRay(transform.position, closestVector, Color.green); return(closestVector * obstacleAvoidMultiplier); } else { inc += rayIncrement; raycastTries++; } } } return(Vector3.zero); }
void Update() { if (provider == null) { return; } if (placingArea) { BoundedPlane plane; if (provider.GetPlane(out plane)) { playArea.transform.position = plane.Center; playArea.transform.rotation = plane.Pose.rotation; float scale = Mathf.Min(1f, plane.Size.x, plane.Size.y); playArea.transform.localScale = Vector3.one * scale; playArea.gameObject.SetActive(true); Vector3 forword = -playArea.transform.forward; forword.y = 0f; Vector3 look = Camera.main.transform.position - playArea.transform.position; look.y = 0f; float angle = Vector3.SignedAngle(look, forword, Vector3.up); if (angle > 135f || angle < -135f) { playArea.transform.Rotate(playArea.transform.up, 180f); } else if (angle > 45f) { playArea.transform.Rotate(playArea.transform.up, -90f); } else if (angle < -45f) { playArea.transform.Rotate(playArea.transform.up, 90f); } HelpUI.ShowPlace(); if (provider.GetClickDown()) { placingArea = false; provider.holdAttachPoint.localPosition = provider.holdAttachPoint.localPosition * scale; provider.holdAttachPoint.localScale = Vector3.one * scale; //UIManager.Instance.GoBackToUI(MainUI); LoadingUI.SetActive(false); HelpUI.gameObject.SetActive(false); playArea.SetArea(); provider.FinishInit(); } } else { playArea.gameObject.SetActive(false); HelpUI.ShowLooking(); } } else if (heldBook != null) { if (provider.GetClickUp()) { heldBook.transform.SetParent(playArea.transform); heldBook.PlaceBook(); heldBook = null; HelpUI.gameObject.SetActive(false); } } else if (currentPlacing == null) { if (currentClickable == null) { #if UNITY_EDITOR || UNITY_STANDALONE if (provider.GetClickDown()) #else if (Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Began && !EventSystem.current.IsPointerOverGameObject(Input.GetTouch(0).fingerId)) #endif { RaycastHit hit; if (Physics.Raycast(provider.GetClickRay(), out hit, Mathf.Infinity, (1 << LayerMask.NameToLayer("Placable")) | (1 << LayerMask.NameToLayer("UI")))) { if (hit.collider.gameObject.layer == LayerMask.NameToLayer("Placable")) { currentClickable = hit.transform.GetComponentInParent <Clickable>(); if (currentClickable != null) { currentClickable.ClickDown(hit); } else if (currentArea.AllowMovement) { currentPlacing = hit.transform.GetComponentInParent <Placable>(); lastPos = currentPlacing.transform.localPosition; placingDown = true; } } } } } else { if (provider.GetClickUp()) { RaycastHit hit; if (Physics.Raycast(provider.GetClickRay(), out hit, Mathf.Infinity, 1 << LayerMask.NameToLayer("Placable"))) { Clickable upClickable = hit.transform.GetComponentInParent <Clickable>(); if (upClickable == currentClickable) { currentClickable.Click(hit); } } currentClickable.ClickUp(hit); currentClickable = null; } } } else { PlaceCurrent(); if (provider.GetClickDown()) { placingDown = true; } else if (placingDown && provider.GetClickUp()) { if (placed) { if (lastPos.HasValue) { if (currentArea != null) { currentArea.MoveInArea(currentPlacing); } } else { if (currentArea != null) { currentArea.AddToArea(currentPlacing); PlayerManager.Instance.RemoveInventory(currentPlacing.Data); } } currentPlacing = null; HelpUI.gameObject.SetActive(false); playArea.ShowPlacing(false); if (HelpManager.Instance.CurrentStep == TutorialStep.PlaceTreat) { HelpManager.Instance.CompleteTutorialStep(TutorialStep.PlaceTreat); } else if (HelpManager.Instance.CurrentStep == TutorialStep.PlaceToy) { HelpManager.Instance.CompleteTutorialStep(TutorialStep.PlaceToy); } placingDown = false; SoundManager.Instance.PlayGroup("PlaceItem"); if (IsNonXR) { GrabBook(BookController.Instance); } } /*else * { * /*if (lastPos.HasValue) * currentPlacing.transform.localPosition = lastPos.Value; * else* * if (currentArea != null) * currentArea.RemoveFromArea(currentPlacing); * PlayerManager.Instance.AddInventory(currentPlacing.Data); * Destroy(currentPlacing.gameObject); * }*/ } } if (currentClickable == null) { #if UNITY_EDITOR || UNITY_STANDALONE if (provider.GetClickDown()) #else if (Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Began && !EventSystem.current.IsPointerOverGameObject(Input.GetTouch(0).fingerId)) #endif { RaycastHit hit; if (Physics.Raycast(provider.GetClickRay(), out hit, Mathf.Infinity)) { if (hit.collider.gameObject.layer == LayerMask.NameToLayer("Base")) { BookController.Instance.ReturnBook(); } } } } }
bool isGrounded() { //Shoot a ray down from center of player to see if we are touching the ground //Length of ray is height from center of player to bottom of player (0.5 in this case) + 0.1 to reach the ground return(Physics.Raycast(this.transform.position, Vector3.down, 1.1f)); }
private void FixedUpdate() { if (move && !talking) { rb.MovePosition(transform.position + transform.forward * 3 * Time.deltaTime); } if (talking) { Vector3 targetDirection = talker.transform.position - transform.position; transform.rotation = Quaternion.LookRotation(targetDirection); } if (!talking) { if (transform.position.z < 2f && transform.position.x > 2f) { Invoking(); transform.rotation = Quaternion.Euler(0, 0, 0); } if (transform.position.z > 2f && transform.position.x < 2f) { Invoking(); transform.rotation = Quaternion.Euler(0, 90, 0); } if (transform.position.z > 2f && transform.position.x > 38f) { Invoking(); transform.rotation = Quaternion.Euler(0, -90, 0); } if (transform.position.z > 38.5f && transform.position.x > 2f) { Invoking(); transform.rotation = Quaternion.Euler(0, 180, 0); } } RaycastHit hit; if (Physics.Raycast(transform.position, transform.forward, out hit, 3) && !talking) { if (hit.transform.gameObject.GetComponent <Human>() != null && hit.transform.gameObject.GetComponent <Human>().talker == null && canTalk) { if (Random.Range(0, 11) > 5) { CancelInvoke("ChangeDirection"); talking = true; canTalk = false; talker = hit.transform.gameObject; hit.transform.gameObject.GetComponent <Human>().talker = gameObject; hit.transform.gameObject.GetComponent <Human>().talking = true; hit.transform.gameObject.GetComponent <Human>().canTalk = false; hit.transform.gameObject.GetComponent <Human>().CancelInvoke("ChangeDirection"); StartCoroutine(Talking()); } } } bubble.SetActive(talking); }
void Awake() { GameObject _gridObj; RaycastHit _objHit; Vector3 _pos; //sets grid array size _grid = new Node[_gridSizeX, _gridSizeZ]; //loops through entire grid for (int z = 0; z < _gridSizeZ; z++) { for (int x = 0; x < _gridSizeX; x++) { //sets position of each grid node _pos = new Vector3(x * 2.25f, 0.0f, z * 2.25f); //checks if floor count is 0 if (_floorCount == 0) { //instantiates floor tile in position _gridObj = Instantiate(_floorDark, _pos, transform.rotation); //sets parent of grid node to grid object _gridObj.transform.parent = transform; //sets grid node with specified values _grid [x, z] = new Node(_gridObj, _counter.ToString(), 0, x, z); //sets floor count to 1 _floorCount = 1; //increases counter _counter++; } else { //instantiates floor tile in position _gridObj = Instantiate(_floorLight, _pos, transform.rotation); //sets parent of grid node to grid object _gridObj.transform.parent = transform; //sets grid node with specified values _grid [x, z] = new Node(_gridObj, _counter.ToString(), 1, x, z); //sets floor count to 0 _floorCount = 0; //increases counter _counter++; } //checks for walkable nodes using raycasts if (Physics.Raycast(_pos, transform.TransformDirection(Vector3.up), out _objHit)) { //checks if collided game object layer is 9 if (_objHit.collider.gameObject.layer == 9) { //sets walkable node to false _grid [x, z]._walkable = false; } } } } }
void EllipseDraw(bool isBtnDown = true) { if (isBtnDown && firstPoint == new Vector2(-1, -1)) { var Ray = Camera.main.ScreenPointToRay(Input.mousePosition); RaycastHit hit; if (Physics.Raycast(Ray, out hit)) { if (UnityEngine.EventSystems.EventSystem.current.IsPointerOverGameObject()) { return; } Vector2 pixelUV = hit.textureCoord; pixelUV.x *= fieldTexture.width; pixelUV.y *= fieldTexture.height; firstPoint = pixelUV; } return; } else if (firstPoint != new Vector2(-1, -1)) { Graphics.CopyTexture(fieldTexture, savedTex); var Ray = Camera.main.ScreenPointToRay(Input.mousePosition); RaycastHit hit; if (Physics.Raycast(Ray, out hit)) { if (UnityEngine.EventSystems.EventSystem.current.IsPointerOverGameObject()) { return; } Vector2 pixelUV = hit.textureCoord; pixelUV.x *= fieldTexture.width; pixelUV.y *= fieldTexture.height; secondPoint = pixelUV; int brushScaleX = (int)(brushSize * Field.transform.localScale.z / Field.transform.localScale.x); int brushScaleY = (int)(brushSize * Field.transform.localScale.x / Field.transform.localScale.z); float deltaX = secondPoint.x - firstPoint.x; float deltaY = secondPoint.y - firstPoint.y; Color[] colors = new Color[brushScaleX * brushScaleY]; for (int i = 0; i < brushScaleX * brushScaleY; i++) { colors[i] = currColor; } float xRadius = System.Math.Abs(deltaX / 2); float yRadius = System.Math.Abs(deltaY / 2); float angle = 20f; int segments = 1000; for (int i = 0; i < (segments + 1); i++) { float x = Mathf.Sin(Mathf.Deg2Rad * angle) * xRadius; float y = Mathf.Cos(Mathf.Deg2Rad * angle) * yRadius; savedTex.SetPixels((int)(x + firstPoint.x + deltaX / 2), (int)(y + firstPoint.y + deltaY / 2), brushScaleX, brushScaleY, colors); angle += (360f / segments); } savedTex.Apply(); fieldMaterial.mainTexture = savedTex; } } if (!isBtnDown) { firstPoint = new Vector2(-1, -1); secondPoint = new Vector2(-1, -1); Graphics.CopyTexture(savedTex, fieldTexture); fieldMaterial.mainTexture = fieldTexture; } }
bool Raycast(Camera cam, Vector2 screenPos, out ScreenRaycastData hitData) { Ray ray = cam.ScreenPointToRay(screenPos); bool didHit = false; hitData = new ScreenRaycastData(); #if !UNITY_3_5 // try to raycast 2D first - this only makes sense on orthographic cameras (physics2D doesnt work with perspective cameras) if (UsePhysics2D && cam.orthographic) { hitData.Hits2D = Physics2D.RaycastAll(ray.origin, Vector2.zero, Mathf.Infinity, ~IgnoreLayerMask); //hitData.Hit2D = Physics2D.Raycast( ray.origin, Vector2.zero, Mathf.Infinity, ~IgnoreLayerMask ); if (hitData.Hits2D.Length > 0) { hitData.Hit2D = hitData.Hits2D[0]; } if (hitData.Hit2D.collider) { hitData.Is2D = true; didHit = true; } } #endif // regular 3D raycast if (!didHit) { hitData.Is2D = false; // ensure this is false if (RayThickness > 0) { didHit = Physics.SphereCast(ray, 0.5f * RayThickness, out hitData.Hit3D, Mathf.Infinity, ~IgnoreLayerMask); } else { didHit = Physics.Raycast(ray, out hitData.Hit3D, Mathf.Infinity, ~IgnoreLayerMask); } } // vizualise ray #if UNITY_EDITOR if (VisualizeRaycasts) { if (didHit) { Vector3 hitPos = hitData.Hit3D.point; #if !UNITY_3_5 if (hitData.Is2D) { hitPos = hitData.Hit2D.point; hitPos.z = hitData.GameObject.transform.position.z; } #endif Debug.DrawLine(ray.origin, hitPos, Color.green, 0.5f); } else { Debug.DrawLine(ray.origin, ray.origin + ray.direction * 9999.0f, Color.red, 0.5f); } } #endif return(didHit); }
void Update() { if (TouchInput) { //touch input not tested if (Input.touches.Length > 0) { RaycastHit hit; Ray ray = Camera.main.ScreenPointToRay(Input.touches[0].position); if (Physics.Raycast(ray, out hit)) { Transform objectHit = hit.transform; if (hit.collider.GetComponent <Interactable>() != null) { hit.collider.GetComponent <Interactable>().Evt_OnInteract.Invoke(); } } } } else { if (Input.GetMouseButtonDown(0)) { if (!EventSystem.current.IsPointerOverGameObject()) { RaycastHit hit; Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition); if (Physics.Raycast(ray, out hit)) { Transform objectHit = hit.transform; if (hit.collider.GetComponent <CameraPosition>() != null) { StartCoroutine(MoveToPosition(hit.collider.GetComponent <CameraPosition>(), 2)); //Camera.main.transform.position = hit.collider.GetComponent<CameraPosition>().transform.position; //Camera.main.transform.rotation = hit.collider.GetComponent<CameraPosition>().transform.rotation; } else if (hit.collider.GetComponent <ObjectViewPosition>() != null) { Camera.main.transform.position = hit.collider.GetComponent <ObjectViewPosition>().transform.position; Camera.main.transform.rotation = hit.collider.GetComponent <ObjectViewPosition>().transform.rotation; Evt_OnSwitchToObjectView.Invoke(); cameraInputScript.AllowRotation = false; } else if (hit.collider.GetComponent <Interactable>() != null) { hit.collider.GetComponent <Interactable>().Evt_OnInteract.Invoke(); } else if (hit.collider.GetComponent <RoomSwitcher>() != null) { hit.collider.GetComponent <RoomSwitcher>().SwitchRooms();; } } } } } }
void Update() { if (_stateMove) //режим движения { if (Input.GetKeyDown(KeyCode.Mouse0)) //переход в режим выбора объектов { Cursor.lockState = CursorLockMode.None; Cursor.visible = true; _playerMove.SwitchState(false); _stateMove = false; Cursor.SetCursor(_cursorStandart, Vector2.zero, CursorMode.ForceSoftware); _stateCursor = 0; } } else //режим выбора объектов { if (!_usedObject) //игрок ни с чем не взаимодействует { _activeObject = null; if (Input.GetKeyDown(KeyCode.Mouse1)) //переход в режим движения { Cursor.lockState = CursorLockMode.Locked; Cursor.visible = false; _playerMove.SwitchState(true); _stateMove = true; _stateCursor = 0; } RaycastHit hit; Ray ray = _playerCamera.ScreenPointToRay(Input.mousePosition); if (Physics.Raycast(ray, out hit) && hit.transform.GetComponent<ActiveObject>()) { Transform objectHit = hit.transform; Vector3 heading = objectHit.position - transform.position; if (heading.sqrMagnitude < _maxRange * _maxRange) { _activeObject = objectHit.GetComponent<ActiveObject>(); TypeObject type = _activeObject.Type; #region Изменение курсора if (type == TypeObject.ActiveSubject && _stateCursor != 1) { Cursor.SetCursor(_cursorUse, Vector2.zero, CursorMode.ForceSoftware); _stateCursor = 1; } else if (type == TypeObject.LookOnlySubject && _stateCursor != 2) { Cursor.SetCursor(_cursorLoupe, Vector2.zero, CursorMode.ForceSoftware); _stateCursor = 2; } else if (type == TypeObject.UsedSubject || type == TypeObject.Take && _stateCursor != 3) { Cursor.SetCursor(_cursorTake, Vector2.zero, CursorMode.ForceSoftware); _stateCursor = 3; } #endregion if (Input.GetKeyDown(KeyCode.Mouse0) && type != TypeObject.None) { if (type == TypeObject.ActiveSubject) { _activeObject = objectHit.GetComponent<ActiveSubject>(); } else if (type == TypeObject.Take || type == TypeObject.UsedSubject) { _activeObject = objectHit.GetComponent<UsedSubject>(); _usedObject = (type == TypeObject.Take) ? objectHit.gameObject : null; } else if (type == TypeObject.LookOnlySubject) { _activeObject = objectHit.GetComponent<LookOnlySubject>(); _usedObject = objectHit.gameObject; Cursor.SetCursor(_cursorStandart, Vector2.zero, CursorMode.ForceSoftware); _stateCursor = 0; } _activeObject.UseObject(this); } } else if (_stateCursor != 0) { Cursor.SetCursor(_cursorStandart, Vector2.zero, CursorMode.ForceSoftware); _stateCursor = 0; } } else if (_stateCursor != 0) { Cursor.SetCursor(_cursorStandart, Vector2.zero, CursorMode.ForceSoftware); _stateCursor = 0; } } else //игрок взаимодействует с объектом { TypeObject type = _activeObject.Type; if (Input.GetKeyDown(KeyCode.Mouse0)) { if (type == TypeObject.LookOnlySubject) { _activeObject.UseObject(this); _usedObject = null; } else if (type == TypeObject.Take) { _activeObject.UseObject(this); _usedObject = null; Cursor.SetCursor(_cursorStandart, Vector2.zero, CursorMode.ForceSoftware); _stateCursor = 0; } else if (type == TypeObject.UsedSubject) { RaycastHit hit; Ray ray = _playerCamera.ScreenPointToRay(Input.mousePosition); if (Physics.Raycast(ray, out hit) && hit.transform.GetComponent<ActiveObject>()) { ActiveObject active = hit.transform.GetComponent<ActiveObject>(); if (active.Type == TypeObject.ActiveSubject) { active.UseObject(this); } } } } else if (Input.GetKeyDown(KeyCode.Mouse1)) { if (type == TypeObject.LookOnlySubject || type == TypeObject.Take) { _activeObject.UseObject(this); _usedObject = null; _activeObject = null; Cursor.lockState = CursorLockMode.Locked; Cursor.visible = false; _playerMove.SwitchState(true); _stateMove = true; _stateCursor = 0; } else if (type == TypeObject.UsedSubject) { _usedObject = null; _activeObject = null; Cursor.SetCursor(_cursorStandart, Vector2.zero, CursorMode.ForceSoftware); _stateCursor = 0; } } } } }
private void LateUpdate() { if (isDying) { return; } if (PauseMenu.GameIsPaused) { animatorTarget.SetFloat("Speed", 0f); return; } if (health < 5) { if (regenCooldown <= 0f) { health++; healthMeter.fillAmount = 0.25f + health * 0.15f; regenCooldown = 2f; } else { regenCooldown -= Time.deltaTime; } } // Toggles aim stance if (Input.GetButtonDown("Fire2")) { if (aiming) { animatorTarget.SetBool("Aiming", false); aiming = false; } else { animatorTarget.SetBool("Aiming", true); animatorTarget.SetFloat("Speed", 0f); aiming = true; } } if (Input.GetButtonDown("Switch") && !hacked) { if (rifleEquipped) { playerController.SetArsenal("Pistol"); rifleEquipped = false; } else { playerController.SetArsenal("AK-74M"); rifleEquipped = true; } aiming = false; } // TODO: Cleanup shooting behavior or move to another class if (!aiming) { Movement(); animatorTarget.SetFloat("Speed", controller.velocity.magnitude); Look(); } else { Look(); if (Input.GetButtonDown("Fire1") && animatorTarget.GetCurrentAnimatorStateInfo(0).IsName("Aiming")) { animatorTarget.SetTrigger("Attack"); if (hacked) { transformTarget.tag = "Player"; transformTarget.gameObject.layer = LayerMask.NameToLayer("Player"); } if (Physics.Raycast(transformTarget.position + gunHeight, transformTarget.forward, out RaycastHit hit, 100, targetLayersMask)) { if (hit.transform.tag == "Enemy") { if (rifleEquipped || hacked) { hit.transform.SendMessage("Killed"); killedEnemies++; } else { if (alerted) { hit.transform.SendMessage("Damage"); } else { hit.transform.SendMessage("Slept"); sleptEnemies++; } } } } if (rifleEquipped || hacked) { akShot.Play(); foreach (GameObject enemy in enemies) { enemy.SendMessage("Caution", transformTarget.position); } } else { tranqShot.Play(); } } } ThirdPersonCamera(); fow.FindTarget(); if (!alerted) { Hack(); if (wasAlerted) { BGM.Instance.Unseen(); } wasAlerted = false; } else { if (hacked) { EndHack(); } if (!wasAlerted) { BGM.Instance.Spotted(); } wasAlerted = true; } alerted = false; }
void Update() { if (PauseMenu.IsOn) { if (Cursor.lockState != CursorLockMode.None) { Cursor.lockState = CursorLockMode.None; } motor.Move(Vector3.zero); motor.Rotate(Vector3.zero); motor.RotateCamera(0f); return; } if (Cursor.lockState != CursorLockMode.Locked) { Cursor.lockState = CursorLockMode.Locked; } //Calculate how high the player should float above ground RaycastHit _hit; if (Physics.Raycast(transform.position, Vector3.down, out _hit, 100f, environmentMask)) { joint.targetPosition = new Vector3(0f, -_hit.point.y, 0f); } else { joint.targetPosition = new Vector3(0f, 0f, 0f); } //calculate movement velocity as a 3D vector float xMov = Input.GetAxisRaw("Horizontal"); float zMov = Input.GetAxisRaw("Vertical"); Vector3 movHorizontal = transform.right * xMov; Vector3 movVertical = transform.forward * zMov; //Final Movement Vector Vector3 _velocity = (movHorizontal + movVertical).normalized * speed; //Apply movement //Takes our velocity above and sends it to motor script motor.Move(_velocity); //Calculate rotation as a 3D vector //Lets us turn the player with the mouse float yRot = Input.GetAxisRaw("Mouse X"); Vector3 _rotation = new Vector3(0f, yRot, 0f) * horizontalSensitivity; //Apply rotation motor.Rotate(_rotation); //Calculate camera rotation as a 3D vector //Lets us turn the camera with the mouse float xRot = Input.GetAxisRaw("Mouse Y"); float _cameraRotationX = xRot * verticalSensitivity; //Apply rotation motor.RotateCamera(_cameraRotationX); //Calculate thruster force based on input Vector3 _thrusterForce = Vector3.zero; if (Input.GetButton("Jump") && thrusterFuelAmount > 0f) { thrusterFuelAmount -= thrusterFuelBurnSpeed * Time.deltaTime; if (thrusterFuelAmount >= 0.02f) { _thrusterForce = Vector3.up * thrusterForce; SetJointSettings(0f); } } else { thrusterFuelAmount += thrsuterFuelRegenSpeed * Time.deltaTime; SetJointSettings(jointSpring); } thrusterFuelAmount = Mathf.Clamp(thrusterFuelAmount, 0f, 1f); //Apply Thruster Force motor.ApplyThruster(_thrusterForce); }
private void Update() { for (int i = 0; i < _currentObjects.Count; i++) { keep(i, false); } if (_hasTarget) { var vector = _targetPosition - transform.position; for (int i = 0; i < Physics.RaycastNonAlloc(transform.position, vector, _hits, vector.magnitude); i++) { var hit = _hits[i]; var obj = hit.collider.gameObject; if (!hit.collider.isTrigger && (_target == null || !Util.InHiearchyOf(obj, _target))) { // Check if already fading int oldIndex = indexOf(_currentObjects, obj); if (oldIndex >= 0) { keep(oldIndex, true); continue; } // Check if was being removed oldIndex = indexOf(_oldObjects, obj); if (oldIndex >= 0) { _currentObjects.Add(_oldObjects[oldIndex]); keep(_currentObjects.Count - 1, true); _oldObjects.RemoveAt(oldIndex); continue; } // Create and add { FadedObject faded; faded.Fade = 0; faded.Object = obj; faded.KeepThisFrame = true; var gotRenderers = obj.GetComponentsInChildren <MeshRenderer>(); faded.Renderers = new FadedRenderer[gotRenderers.Length]; for (int k = 0; k < gotRenderers.Length; k++) { FadedRenderer renderer; renderer.Renderer = gotRenderers[k]; renderer.OriginalMaterial = Material.Instantiate(renderer.Renderer.material); renderer.NewMaterial = Material.Instantiate(renderer.Renderer.material); renderer.OriginalColor = renderer.OriginalMaterial.color; renderer.Renderer.material = renderer.NewMaterial; renderer.Renderer.gameObject.SendMessage("OnFade", SendMessageOptions.DontRequireReceiver); faded.Renderers[k] = renderer; } _currentObjects.Add(faded); } } } } for (int i = _currentObjects.Count - 1; i >= 0; i--) { if (!_currentObjects[i].KeepThisFrame) { _oldObjects.Add(_currentObjects[i]); _currentObjects.RemoveAt(i); } } for (int i = 0; i < _currentObjects.Count; i++) { var value = _currentObjects[i]; value.Fade = Mathf.Lerp(value.Fade, 1.0f, Time.deltaTime * Speed); fade(value.Renderers, value.Fade); _currentObjects[i] = value; } for (int i = _oldObjects.Count - 1; i >= 0; i--) { var value = _oldObjects[i]; value.Fade = Mathf.Lerp(value.Fade, 0, Time.deltaTime * Speed); fade(value.Renderers, value.Fade); if (value.Fade > float.Epsilon) { _oldObjects[i] = value; } else { foreach (var renderer in _oldObjects[i].Renderers) { renderer.Renderer.material = renderer.OriginalMaterial; renderer.Renderer.gameObject.SendMessage("OnUnfade", SendMessageOptions.DontRequireReceiver); } _oldObjects.RemoveAt(i); } } }
// Update is called once per frame void Update() { curtime += Time.deltaTime; nadeTime += Time.deltaTime; // IF left mouse click pressed -> shoot if (Input.GetMouseButtonDown(0)) { mousedown = true; } if (Input.GetMouseButtonUp(0)) { mousedown = false; } //IF E key pressed -> Throw Grenade if (Input.GetKeyDown(KeyCode.E)) { //Debug.Log("G is pressed"); grenadeThrown = true; } if (Input.GetKeyUp(KeyCode.E)) { //Debug.Log("G is releasd"); grenadeThrown = false; } //Right click for raycast testing if (Input.GetMouseButtonDown(1)) { RaycastHit hit; Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition); if (Physics.Raycast(ray, out hit, 100.0f)) { //Destroy(hit.transform.gameObject); // Draws raycast line in scene // DrawRay (start position, end position, color, duration of time ) Debug.DrawRay(transform.position, Camera.main.transform.forward * 10, Color.green, 10.0f); //Debug.Log("You hit the " + hit.transform.name); // ensure you picked right object Vector3 pointOfCollision = hit.point; //Debug.Log("Hit at point: " + pointOfCollision.ToString("F4")); } } if (mousedown && curtime > fireRate) { Vector3 dir = new Vector3(transform.position.x, transform.position.y, transform.position.z); GameObject bull = Instantiate(bullet, Camera.main.transform.position + Camera.main.transform.forward / 2, Camera.main.transform.rotation); //Debug.Log(Camera.main.transform.forward); bull.tag = "Bullet"; Rigidbody rig = bull.GetComponent <Rigidbody>(); rig.useGravity = false; rig.AddForce(cam.forward); curtime = 0; // Reset rate of fire timer } if (grenadeThrown && nadeTime > fireRate) { Vector3 dir = new Vector3(transform.position.x, transform.position.y, transform.position.z); GameObject nade = Instantiate(grenade, Camera.main.transform.position + Camera.main.transform.forward / 2, Camera.main.transform.rotation); nade.tag = "Explosive"; Rigidbody rig = nade.GetComponent <Rigidbody>(); rig.useGravity = false; rig.AddForce(cam.forward); nadeTime = 0; // Reset nade throw timer } }
public override void FindNext() { RaycastHit hit; List <MirrorCube> FoundMirrors = new List <MirrorCube>(); for (int i = 0; i < 5; i++) { switch (i) { case (0): if (Physics.Raycast(this.transform.position, -Vector3.forward, out hit, Mathf.Infinity)) { if (hit.collider.TryGetComponent(out Cube c)) { //Debug.Log(c.name); FireParticle(-Vector3.forward); if (hit.collider.GetComponent <MirrorCube>() == true) { foundMirror = true; c.FlipOn(); FoundMirrors.Add(hit.collider.GetComponent <MirrorCube>()); } else { c.FlipOn(); } } } break; case (1): if (Physics.Raycast(this.transform.position, -Vector3.right, out hit, Mathf.Infinity)) { if (hit.collider.TryGetComponent(out Cube c)) { //Debug.Log(c.name); FireParticle(-Vector3.right); if (hit.collider.GetComponent <MirrorCube>() == true) { foundMirror = true; c.FlipOn(); FoundMirrors.Add(hit.collider.GetComponent <MirrorCube>()); } else { c.FlipOn(); } } } break; case (2): if (Physics.Raycast(this.transform.position, Vector3.forward, out hit, Mathf.Infinity)) { if (hit.collider.TryGetComponent(out Cube c)) { //Debug.Log(c.name); FireParticle(Vector3.forward); if (hit.collider.GetComponent <MirrorCube>() == true) { foundMirror = true; c.FlipOn(); FoundMirrors.Add(hit.collider.GetComponent <MirrorCube>()); } else { c.FlipOn(); } } } break; case (3): if (Physics.Raycast(this.transform.position, Vector3.right, out hit, Mathf.Infinity)) { if (hit.collider.TryGetComponent(out Cube c)) { //Debug.Log(c.name); FireParticle(Vector3.right); if (hit.collider.GetComponent <MirrorCube>() == true) { foundMirror = true; c.FlipOn(); FoundMirrors.Add(hit.collider.GetComponent <MirrorCube>()); } else { c.FlipOn(); } } } break; case (4): if (foundMirror == false) { CheckWin(); } else { foundMirror = false; for (int j = 0; j < FoundMirrors.Count; j++) { FoundMirrors[j].MirrorFunction(this, Vector3.zero); } } break; } } }
private void FixedUpdate() { // apply the impact force: if (m_Impact.magnitude > 0.2) { m_CharacterController.Move(m_Impact * Time.deltaTime); } // consumes the m_Impact energy each cycle: m_Impact = Vector3.Lerp(m_Impact, Vector3.zero, 5 * Time.deltaTime); // apply gravity forces if (m_CharacterController.isGrounded) { m_MoveDir.y = -m_StickToGroundForce; } else { m_MoveDir += Physics.gravity * m_GravityMultiplier * Time.fixedDeltaTime; } // movement bool canMove = !m_Animator.GetBool("isGuarding") && !m_Animator.GetBool("isKnockdowned"); // you can be changed later if (canMove) { float speed; SetLocomotionInput(out speed); // always move along the camera forward as it is the direction that it being aimed at Vector3 desiredMove = transform.forward * m_LocomotionInput.y + transform.right * m_LocomotionInput.x; // get a normal for the surface that is being touched to move along it RaycastHit hitInfo; Physics.SphereCast(transform.position, m_CharacterController.radius, Vector3.down, out hitInfo, m_CharacterController.height / 2f, Physics.AllLayers, QueryTriggerInteraction.Ignore); desiredMove = Vector3.ProjectOnPlane(desiredMove, hitInfo.normal).normalized; m_MoveDir.x = desiredMove.x * speed; m_MoveDir.z = desiredMove.z * speed; // dash if (m_CanDash) { m_Animator.SetTrigger("dash"); m_MoveDir.x = m_MoveDir.x * m_DashThrust; m_MoveDir.y = m_DashHeight; m_MoveDir.z = m_MoveDir.z * m_DashThrust; AddImpact(m_MoveDir, m_DashThrust); m_CanDash = false; } ProgressStepCycle(speed); } else { // if guarding make sure they cant move m_MoveDir.x = 0f; m_MoveDir.z = 0f; } m_CollisionFlags = m_CharacterController.Move(m_MoveDir * Time.fixedDeltaTime); m_MouseLook.UpdateCursorLock(); }
void RectDraw(bool isBtnDown = true) { if (isBtnDown && firstPoint == new Vector2(-1, -1)) { var Ray = Camera.main.ScreenPointToRay(Input.mousePosition); RaycastHit hit; if (Physics.Raycast(Ray, out hit)) { if (UnityEngine.EventSystems.EventSystem.current.IsPointerOverGameObject()) { return; } Vector2 pixelUV = hit.textureCoord; pixelUV.x *= fieldTexture.width; pixelUV.y *= fieldTexture.height; firstPoint = pixelUV; } return; } else if (firstPoint != new Vector2(-1, -1)) { Graphics.CopyTexture(fieldTexture, savedTex); var Ray = Camera.main.ScreenPointToRay(Input.mousePosition); RaycastHit hit; if (Physics.Raycast(Ray, out hit)) { if (UnityEngine.EventSystems.EventSystem.current.IsPointerOverGameObject()) { return; } Vector2 pixelUV = hit.textureCoord; pixelUV.x *= fieldTexture.width; pixelUV.y *= fieldTexture.height; secondPoint = pixelUV; int brushScaleX = (int)(brushSize * Field.transform.localScale.z / Field.transform.localScale.x); int brushScaleY = (int)(brushSize * Field.transform.localScale.x / Field.transform.localScale.z); float deltaX = secondPoint.x - firstPoint.x; float deltaY = secondPoint.y - firstPoint.y; Color[] colors = new Color[brushScaleX * brushScaleY]; for (int i = 0; i < brushScaleX * brushScaleY; i++) { colors[i] = currColor; } for (int i = 0; i <= System.Math.Abs((int)(deltaX / brushScaleX)); i++) { int d = deltaX <= 0 ? -i : i; savedTex.SetPixels((int)(firstPoint.x + d * brushScaleX), (int)firstPoint.y, brushScaleX, brushScaleY, colors); savedTex.SetPixels((int)(secondPoint.x - d * brushScaleX), (int)secondPoint.y, brushScaleX, brushScaleY, colors); } for (int i = 0; i <= System.Math.Abs((int)(deltaY / brushScaleY)); i++) { int d = deltaY <= 0 ? -i : i; savedTex.SetPixels((int)firstPoint.x, (int)(firstPoint.y + d * brushScaleY), brushScaleX, brushScaleY, colors); savedTex.SetPixels((int)secondPoint.x, (int)(secondPoint.y - d * brushScaleY), brushScaleX, brushScaleY, colors); } savedTex.SetPixels((int)firstPoint.x, (int)firstPoint.y, brushScaleX, brushScaleY, colors); savedTex.SetPixels((int)secondPoint.x, (int)secondPoint.y, brushScaleX, brushScaleY, colors); savedTex.SetPixels((int)(firstPoint.x + deltaX), (int)firstPoint.y, brushScaleX, brushScaleY, colors); savedTex.SetPixels((int)firstPoint.x, (int)(firstPoint.y + deltaY), brushScaleX, brushScaleY, colors); savedTex.Apply(); fieldMaterial.mainTexture = savedTex; } } if (!isBtnDown) { firstPoint = new Vector2(-1, -1); secondPoint = new Vector2(-1, -1); Graphics.CopyTexture(savedTex, fieldTexture); fieldMaterial.mainTexture = fieldTexture; } }
// Update is called once per frame void FixedUpdate() { mergeMaterial.SetInt(ShowBackground, IsBackgroundVisible ? 1 : 0); var paintBrush = _brushes.FirstOrDefault(); if (!paintBrush) { return; } var ray = paintBrush.GetRay(); var hitCount = Physics.RaycastNonAlloc(ray, _hits, paintBrush.rayLength); if (hitCount == 0) { ray.direction *= -1; hitCount = Physics.RaycastNonAlloc(ray, _hits, paintBrush.rayLength); } for (int i = 0; i < hitCount; i++) { var hitInfo = _hits[i]; if (hitInfo.transform != transform) { continue; } var hitInfoTextureCoord = hitInfo.textureCoord; maskMaterial.SetColor(DrawColor, Color.blue); maskMaterial.SetFloat(BrushStrength, paintBrush.Strength); maskMaterial.SetVector(Coordinate, new Vector4(hitInfoTextureCoord.x, hitInfoTextureCoord.y, 0, 0)); maskMaterial.SetFloat(BrushSize, paintBrush.Size); var tempMask = RenderTexture.GetTemporary(1024, 1024, 0, RenderTextureFormat.ARGB64); Graphics.Blit(null, tempMask, maskMaterial); Graphics.Blit(tempMask, maskTexture); RenderTexture.ReleaseTemporary(tempMask); colorMaterial.SetColor(DrawColor, paintBrush.Color); colorMaterial.SetFloat(BrushStrength, paintBrush.Strength); colorMaterial.SetVector(Coordinate, new Vector4(hitInfoTextureCoord.x, hitInfoTextureCoord.y, 0, 0)); colorMaterial.SetFloat(BrushSize, paintBrush.Size); var tempColor = RenderTexture.GetTemporary(1024, 1024, 0, RenderTextureFormat.ARGB64); Graphics.Blit(null, tempColor, colorMaterial); Graphics.Blit(tempColor, colorTexture); RenderTexture.ReleaseTemporary(tempColor); // } }
// Update is called once per frame void Update() { //if player is out if (hp < 1 && OUT == false) { anim.SetBool("isOut", true); Debug.Log("Player OUT! AAAAAAAAAAAAAAAAHH"); hpText.text = "KO!"; OUT = true; gameManager.falseHeroCount--; } /* * if (isActive && actionCount > 0 && gameManager.playerTurn == true) * { * Ray ray = cam.ScreenPointToRay(Input.mousePosition); //take current mouse position and make a ray in that direction * RaycastHit hit; * * * //if mouse is over the playing field * if (Physics.Raycast(ray, out hit)) * { * drawLine(hit.point); * * * //Check for left mouse button * if (Input.GetMouseButtonDown(0) && gameManager.teamActionCount > 0) * { * if (inRange <= actionCount && inRange <= gameManager.teamActionCount && inRange != 0) * { * moveUnit(hit.point); * } * } * * } * * } */ if (agent.remainingDistance <= 0.1 && isMoving == true && OUT == false) { isMoving = false; audioSource.Stop(); Vector3 newVector = new Vector3(gameObject.transform.position.x, (transform.position.y + 1), transform.position.z); RaycastHit hit; Physics.Raycast(newVector, -Vector3.up, out hit); Debug.Log(hit.collider.gameObject); Tile currentTile = hit.transform.gameObject.GetComponent <Tile>(); defenseNorth = currentTile.northCover; defenseSouth = currentTile.southCover; defenseEast = currentTile.eastCover; defenseWest = currentTile.westCover; anim.SetBool("isRunning", false); if (defenseNorth + defenseSouth + defenseEast + defenseWest > 0) { anim.SetBool("isCrouching", true); } else { anim.SetBool("isCrouching", false); } } if (!isActive && lineOn == true || gameManager.playerTurn == false && lineOn == true && OUT == false) { LineRenderer line = GetComponent <LineRenderer>(); Destroy(line); lineOn = false; } }
void CheckPlayerZhuPaoFireBt() { if (!ScreenDanHeiCtrl.IsStartGame) { return; } // if (!XkGameCtrl.IsActivePlayerTwo) { // return; // } if (XkGameCtrl.GetInstance().m_GamePlayerAiData.IsActiveAiPlayer == true) { //激活主角Ai坦克状态. if (XkGameCtrl.GetInstance().m_AiPathGroup.m_CameraMoveType == AiPathGroupCtrl.MoveState.YuLe) { if (Random.Range(0, 100) % 3 != 0) { return; } } else { if (Random.Range(0, 100) % 30 != 0) { return; } } } else { if (!IsActiveFireBtZP) { return; } if (!CheckIsActivePlayer()) { return; } } // if (DaoJiShiCtrl.GetInstance().GetIsPlayDaoJishi()) { // return; // } if (Camera.main == null) { return; } if (GameOverCtrl.IsShowGameOver || JiFenJieMianCtrl.GetInstance().GetIsShowFinishTask()) { if (GameOverCtrl.IsShowGameOver) { IsActiveFireBtZP = false; } return; } bool isSpawnAmmo = CheckIsSpawnPlayerAmmo(ZHU_PAO_INDEX); if (!isSpawnAmmo) { return; } LastFireTimeZhuPao = Time.time; CheckPlayerHouZuoLi(ZhuPaoAmmoSt, ZHU_PAO_INDEX); Vector3 ammoSpawnForward = AmmoStartPosZP[0].forward; Vector3 ammoSpawnPos = AmmoStartPosZP[0].position; Quaternion ammoSpawnRot = AmmoStartPosZP[0].rotation; GameObject obj = null; CheckFireAudioPlayerZhuPao(); //pcvr.OpenZuoYiQiNang(PlayerIndex); //pcvr.GetInstance().ActiveFangXiangDouDong(PlayerIndex, false); obj = SpawnPlayerAmmoByAmmoType(ZHU_PAO_INDEX, ammoSpawnPos, ammoSpawnRot); if (obj == null) { return; } obj.transform.parent = XkGameCtrl.PlayerAmmoArray; PlayerAmmoCtrl ammoScript = obj.GetComponent<PlayerAmmoCtrl>(); Vector3 mousePosInput = Input.mousePosition; //if (pcvr.bIsHardWare) { //mousePosInput = pcvr.CrossPositionTwo; //} Vector3 firePos = Vector3.zero; Vector3 mousePos = mousePosInput + Vector3.forward * OffsetForward; Vector3 posTmp = Camera.main.ScreenToWorldPoint(mousePos); Vector3 ammoForward = Vector3.Normalize( posTmp - ammoSpawnPos ); RaycastHit hit; if (!IsPSAutoFire) { firePos = FirePosValTmp * ammoSpawnForward + ammoSpawnPos; FireRayDirLen = ammoScript.MvSpeed * ammoScript.LiveTime; if (Physics.Raycast(ammoSpawnPos, ammoSpawnForward, out hit, FireRayDirLen, FireLayer.value)) { //Debug.Log("Unity:"+"Player fire obj -> "+hit.collider.name); if (ammoScript.AmmoType != PlayerAmmoType.ChuanTouAmmo) { firePos = hit.point; } } } else { ammoForward = obj.transform.forward; firePos = FirePosValTmp * ammoForward + ammoSpawnPos; if (Physics.Raycast(ammoSpawnPos, ammoForward, out hit, FireRayDirLen, FireLayer.value)) { //Debug.Log("Unity:"+"Player fire obj -> "+hit.collider.name); if (ammoScript.AmmoType != PlayerAmmoType.ChuanTouAmmo) { firePos = hit.point; } } } ammoScript.StartMoveAmmo(firePos, PlayerIndex); }
private void Update() { Ray interactionRay = Camera.main.ScreenPointToRay(Input.mousePosition); RaycastHit interactionInfo; if (Physics.Raycast(interactionRay, out interactionInfo, Mathf.Infinity)) { if (currentBuilding != null) { Node nodeToChange = grid.NodeFromWorldPoint(interactionInfo.point); Vector3 moveTransform = nodeToChange.nodeWorldPosition; currentBuilding.transform.position = moveTransform; if (Input.GetKeyUp(KeyCode.R)) { currentBuilding.transform.Rotate(currentBuilding.transform.rotation.x, currentBuilding.transform.rotation.y + 90, currentBuilding.transform.rotation.z); } if (Input.GetMouseButtonUp(0) && hitBuilding == false && !EventSystem.current.IsPointerOverGameObject()) { UnitManager.instance.buildMode = false; Destroy(currentBuilding.GetComponent <Rigidbody>()); currentBuilding.GetComponent <Collider>().isTrigger = true; for (int i = 0; i < currentBuilding.GetComponent <DynamicObstacle>().buildingTransforms.Count; i++) { Vector3 posToScan = currentBuilding.GetComponent <DynamicObstacle>().buildingTransforms[i].position; Node nodeToScan = grid.NodeFromWorldPoint(posToScan); nodeToScan.walkable = false; currentBuilding.GetComponent <DynamicObstacle>().occupiedNodes.Add(nodeToScan); Destroy(currentBuilding.GetComponent <DynamicObstacle>().buildingTransforms[i].gameObject); } if (UnitManager.instance.movingUnits.Count > 0) { Debug.Log("Number of units in unit manager: " + UnitManager.instance.movingUnits.Count); for (int i = 0; i < UnitManager.instance.movingUnits.Count; i++) { for (int y = 0; y < UnitManager.instance.movingUnits[i].GetComponent <Unit>().path.Length; y++) { for (int z = 0; z < currentBuilding.GetComponent <DynamicObstacle>().occupiedNodes.Count; z++) { if (UnitManager.instance.movingUnits[i].GetComponent <Unit>().path[y] == currentBuilding.GetComponent <DynamicObstacle>().occupiedNodes[z].nodeWorldPosition) { UnitManager.instance.movingUnits[i].GetComponent <Unit>().stopMoving = true; UnitManager.instance.movingUnits[i].GetComponent <Unit>().moveFSM = Unit.MoveFSM.recalculatePath; break; } } } } } GameObject building = currentBuilding; building.name = "Building"; building.layer = LayerMask.NameToLayer("Unwalkable"); building.transform.position = currentBuilding.transform.position; currentBuilding = null; } } if (interactionInfo.collider.transform.gameObject.name == "Building" && Input.GetKeyDown(KeyCode.B)) { GameObject buildingToDestroy = interactionInfo.collider.transform.gameObject; for (int i = 0; i < buildingToDestroy.GetComponent <DynamicObstacle>().occupiedNodes.Count; i++) { buildingToDestroy.GetComponent <DynamicObstacle>().occupiedNodes[i].walkable = true; } Destroy(buildingToDestroy); } } }
/// <summary> /// Checks for hits on the target objects, highlighting when found /// </summary> public void Update() { // If the left mouse button is pressed if (!ALREADY_CLICKED && Input.GetMouseButtonDown(0)) { // Detect the object(s) the user has clicked Ray ray = gizmoCamera.ScreenPointToRay(Input.mousePosition); RaycastHit[] hits = Physics.RaycastAll(ray, gizmoLayer); bool detected = false; pressingPlane = false; // Check if object are our targets (skipping the collision if the renderer isn't enabled) foreach (RaycastHit hit in hits) { if (Array.IndexOf(targets, hit.collider.gameObject) >= 0) { if (!hit.collider.gameObject.GetComponent <Renderer>().enabled) { continue; } if (hit.collider.gameObject.name.Contains("_plane_")) { pressingPlane = true; } detected = true; pressing = true; } } if (detected) { // Store the current materials of the targets, then highlight them if (previousMaterials != null) { previousMaterials.Clear(); } foreach (GameObject target in targets) { try { foreach (MeshRenderer renderer in target.GetComponentsInChildren <MeshRenderer>(false)) { previousMaterials[renderer] = renderer.sharedMaterial; renderer.material = highlight; } } catch (NullReferenceException exception) { // Perhaps no previous materials could be found? } } ALREADY_CLICKED = true; } } else if (Input.GetMouseButtonUp(0) && previousMaterials.Count > 0) { // If the left mouse button was released and we haven't un-highlighted yet foreach (MeshRenderer renderer in previousMaterials.Keys) { renderer.material = previousMaterials[renderer]; } previousMaterials.Clear(); pressing = false; pressingPlane = false; ALREADY_CLICKED = false; } }
// Update is called once per frame void Update() { if (fpsOn) { return; } if (Time.timeScale == 1) { deltaT = Time.deltaTime; } else if (Time.timeScale > 1) { deltaT = Time.deltaTime / Time.timeScale; } else { deltaT = 0.015f; } #if UNITY_IPHONE || UNITY_ANDROID || UNITY_WP8 || UNITY_BLACKBERRY if (enableTouchPan) { Quaternion camDir = Quaternion.Euler(0, transform.eulerAngles.y, 0); if (Input.touchCount == 1) { Touch touch = Input.touches[0]; if (touch.phase == TouchPhase.Moved) { Vector3 deltaPos = touch.position; if (lastTouchPos != new Vector3(9999, 9999, 9999)) { deltaPos = deltaPos - lastTouchPos; moveDir = new Vector3(deltaPos.x, 0, deltaPos.y).normalized *-1; } lastTouchPos = touch.position; } } else { lastTouchPos = new Vector3(9999, 9999, 9999); } Vector3 dir = thisT.InverseTransformDirection(camDir * moveDir) * 1.5f; thisT.Translate(dir * panSpeed * deltaT); moveDir = moveDir * (1 - deltaT * 5); } if (enableTouchZoom) { if (Input.touchCount == 2) { Touch touch1 = Input.touches[0]; Touch touch2 = Input.touches[1]; //~ Vector3 zoomScreenPos=(touch1.position+touch2.position)/2; if (touch1.phase == TouchPhase.Moved && touch1.phase == TouchPhase.Moved) { Vector3 dirDelta = (touch1.position - touch1.deltaPosition) - (touch2.position - touch2.deltaPosition); Vector3 dir = touch1.position - touch2.position; float dot = Vector3.Dot(dirDelta.normalized, dir.normalized); if (Mathf.Abs(dot) > 0.7f) { touchZoomSpeed = dir.magnitude - dirDelta.magnitude; } } } if (touchZoomSpeed < 0) { if (Vector3.Distance(camT.position, thisT.position) < maxZoomDistance) { camT.Translate(Vector3.forward * Time.deltaTime * zoomSpeed * touchZoomSpeed); currentZoom += Time.deltaTime * zoomSpeed * touchZoomSpeed; } } else if (touchZoomSpeed > 0) { if (Vector3.Distance(camT.position, thisT.position) > minZoomDistance) { camT.Translate(Vector3.forward * Time.deltaTime * zoomSpeed * touchZoomSpeed); currentZoom += Time.deltaTime * zoomSpeed * touchZoomSpeed; } } touchZoomSpeed = touchZoomSpeed * (1 - Time.deltaTime * 5); } if (enableTouchRotate) { if (Input.touchCount == 2) { Touch touch1 = Input.touches[0]; Touch touch2 = Input.touches[1]; Vector2 delta1 = touch1.deltaPosition.normalized; Vector2 delta2 = touch2.deltaPosition.normalized; Vector2 delta = (delta1 + delta2) / 2; float rotX = thisT.rotation.eulerAngles.x - delta.y * rotationSpeed; float rotY = thisT.rotation.eulerAngles.y + delta.x * rotationSpeed; rotX = Mathf.Clamp(rotX, minRotateAngle, maxRotateAngle); //~ Quaternion rot=Quaternion.Euler(delta.y, delta.x, 0); //Debug.Log(rotX+" "+rotY); thisT.rotation = Quaternion.Euler(rotX, rotY, 0); //thisT.rotation*=rot; } } #endif #if UNITY_EDITOR || !(UNITY_IPHONE && UNITY_ANDROID && UNITY_WP8 && UNITY_BLACKBERRY) //mouse and keyboard if (enableMouseRotate) { if (Input.GetMouseButtonDown(1)) { initialMousePosX = Input.mousePosition.x; initialMousePosY = Input.mousePosition.y; initialRotX = thisT.eulerAngles.y; initialRotY = thisT.eulerAngles.x; } if (Input.GetMouseButton(1)) { float deltaX = Input.mousePosition.x - initialMousePosX; float deltaRotX = (.1f * (initialRotX / Screen.width)); float rotX = deltaX + deltaRotX; float deltaY = initialMousePosY - Input.mousePosition.y; float deltaRotY = -(.1f * (initialRotY / Screen.height)); float rotY = deltaY + deltaRotY; float y = rotY + initialRotY; //limit the rotation if (y > maxRotateAngle) { initialRotY -= (rotY + initialRotY) - maxRotateAngle; y = maxRotateAngle; } else if (y < minRotateAngle) { initialRotY += minRotateAngle - (rotY + initialRotY); y = minRotateAngle; } thisT.rotation = Quaternion.Euler(y, rotX + initialRotX, 0); } } Quaternion direction = Quaternion.Euler(0, thisT.eulerAngles.y, 0); if (enableKeyPanning) { if (Input.GetButton("Horizontal")) { Vector3 dir = transform.InverseTransformDirection(direction * Vector3.right); thisT.Translate(dir * panSpeed * deltaT * Input.GetAxisRaw("Horizontal")); } if (Input.GetButton("Vertical")) { Vector3 dir = transform.InverseTransformDirection(direction * Vector3.forward); thisT.Translate(dir * panSpeed * deltaT * Input.GetAxisRaw("Vertical")); } } if (enableMousePanning) { Vector3 mousePos = Input.mousePosition; Vector3 dirHor = transform.InverseTransformDirection(direction * Vector3.right); if (mousePos.x <= 0) { thisT.Translate(dirHor * panSpeed * deltaT * -3); } else if (mousePos.x <= mousePanningZoneWidth) { thisT.Translate(dirHor * panSpeed * deltaT * -1); } else if (mousePos.x >= Screen.width) { thisT.Translate(dirHor * panSpeed * deltaT * 3); } else if (mousePos.x > Screen.width - mousePanningZoneWidth) { thisT.Translate(dirHor * panSpeed * deltaT * 1); } Vector3 dirVer = transform.InverseTransformDirection(direction * Vector3.forward); if (mousePos.y <= 0) { thisT.Translate(dirVer * panSpeed * deltaT * -3); } else if (mousePos.y <= mousePanningZoneWidth) { thisT.Translate(dirVer * panSpeed * deltaT * -1); } else if (mousePos.y >= Screen.height) { thisT.Translate(dirVer * panSpeed * deltaT * 3); } else if (mousePos.y > Screen.height - mousePanningZoneWidth) { thisT.Translate(dirVer * panSpeed * deltaT * 1); } } if (enableMouseZoom) { float zoomInput = Input.GetAxis("Mouse ScrollWheel"); if (zoomInput != 0) { currentZoom += zoomSpeed * zoomInput; currentZoom = Mathf.Clamp(currentZoom, -maxZoomDistance, -minZoomDistance); } } #endif if (avoidClipping) { Vector3 aPos = thisT.TransformPoint(new Vector3(0, 0, currentZoom)); Vector3 dirC = aPos - thisT.position; float dist = Vector3.Distance(aPos, thisT.position); RaycastHit hit; obstacle = Physics.Raycast(thisT.position, dirC, out hit, dist); if (!obstacle) { float camZ = Mathf.Lerp(camT.localPosition.z, currentZoom, Time.deltaTime * 4); camT.localPosition = new Vector3(camT.localPosition.x, camT.localPosition.y, camZ); } else { dist = Vector3.Distance(hit.point, thisT.position) * 0.85f; float camZ = Mathf.Lerp(camT.localPosition.z, -dist, Time.deltaTime * 50); camT.localPosition = new Vector3(camT.localPosition.x, camT.localPosition.y, camZ); } } else { float camZ = Mathf.Lerp(camT.localPosition.z, currentZoom, Time.deltaTime * 4); camT.localPosition = new Vector3(camT.localPosition.x, camT.localPosition.y, camZ); } float x = Mathf.Clamp(thisT.position.x, minPosX, maxPosX); float z = Mathf.Clamp(thisT.position.z, minPosZ, maxPosZ); thisT.position = new Vector3(x, thisT.position.y, z); }
void Update() { switch (minionId) { case 1: this.gameObject.renderer.material.color = Color.red; break; case 2: this.gameObject.renderer.material.color = Color.blue; break; case 3: this.gameObject.renderer.material.color = Color.yellow; break; case 4: this.gameObject.renderer.material.color = Color.green; break; } //Move towards the target node if (targetNode != null && Network.isServer) { Vector3 targetPosition = new Vector3(targetNode.x, transform.position.y, targetNode.z); gameObject.transform.position = Vector3.MoveTowards(transform.position, targetPosition, moveSpeed); //Check if it reached the target if (transform.position == targetPosition) { //Destroy the object //GameObject.FindGameObjectWithTag("MinionController").GetComponent<MinionController>().minionsSpawned--; GameObject[] players = GameObject.FindGameObjectsWithTag("Player"); foreach (GameObject p in players) { MinionController mc = p.GetComponent <MinionController>(); if (mc.id == minionId) { mc.networkView.RPC("MinusMinion", RPCMode.AllBuffered); break; } } Collider[] hitColliders = Physics.OverlapSphere(transform.position, 1.0f); int i = 0; while (i < hitColliders.Length) { if (hitColliders[i].gameObject.tag == "SparkPoint") { hitColliders[i].gameObject.networkView.RPC("MinionCapture", RPCMode.AllBuffered, minionId); break; } i++; } Network.Destroy(GetComponent <NetworkView> ().viewID); //Destroy(gameObject); } } }
/// <summary> /// This method is called in a batch from ListenerFollower /// </summary> /// <returns></returns> public bool RayCastForOcclusion() { DoneWithOcclusion(); var raycastOrigin = Trans.position; var offset = RayCastOriginOffset; if (offset > 0) { raycastOrigin = Vector3.MoveTowards(raycastOrigin, _listenerThisFrame.position, offset); } var direction = _listenerThisFrame.position - raycastOrigin; var distanceToListener = direction.magnitude; if (distanceToListener > VarAudio.maxDistance) { // out of hearing range, no reason to calculate occlusion. MasterAudio.AddToOcclusionOutOfRangeSources(GrpVariation.GameObj); ResetToNonOcclusionSetting(); return(false); } MasterAudio.AddToOcclusionInRangeSources(GrpVariation.GameObj); var is2DRaycast = _maThisFrame.occlusionRaycastMode == MasterAudio.RaycastMode.Physics2D; if (GrpVariation.LowPassFilter == null) { // in case Occlusion got turned on during runtime. var newFilter = GrpVariation.gameObject.AddComponent <AudioLowPassFilter>(); GrpVariation.LowPassFilter = newFilter; } #if PHY2D_ENABLED var oldQueriesStart = Physics2D.queriesStartInColliders; if (is2DRaycast) { Physics2D.queriesStartInColliders = _maThisFrame.occlusionIncludeStartRaycast2DCollider; } #endif #if PHY2D_ENABLED || PHY3D_ENABLED var oldRaycastsHitTriggers = true; #endif // ReSharper disable once ConvertIfStatementToConditionalTernaryExpression if (is2DRaycast) { #if PHY2D_ENABLED oldRaycastsHitTriggers = Physics2D.queriesHitTriggers; Physics2D.queriesHitTriggers = _maThisFrame.occlusionRaycastsHitTriggers; #endif } else { #if PHY3D_ENABLED oldRaycastsHitTriggers = Physics.queriesHitTriggers; Physics.queriesHitTriggers = _maThisFrame.occlusionRaycastsHitTriggers; #endif } var hitPoint = Vector3.zero; float?hitDistance = null; var isHit = false; if (_maThisFrame.occlusionUseLayerMask) { switch (_maThisFrame.occlusionRaycastMode) { case MasterAudio.RaycastMode.Physics3D: #if PHY3D_ENABLED RaycastHit hitObject; if (Physics.Raycast(raycastOrigin, direction, out hitObject, distanceToListener, _maThisFrame.occlusionLayerMask.value)) { isHit = true; hitPoint = hitObject.point; hitDistance = hitObject.distance; } #endif break; case MasterAudio.RaycastMode.Physics2D: #if PHY2D_ENABLED var castHit2D = Physics2D.Raycast(raycastOrigin, direction, distanceToListener, _maThisFrame.occlusionLayerMask.value); if (castHit2D.transform != null) { isHit = true; hitPoint = castHit2D.point; hitDistance = castHit2D.distance; } #endif break; } } else { switch (_maThisFrame.occlusionRaycastMode) { case MasterAudio.RaycastMode.Physics3D: #if PHY3D_ENABLED RaycastHit hitObject; if (Physics.Raycast(raycastOrigin, direction, out hitObject, distanceToListener)) { isHit = true; hitPoint = hitObject.point; hitDistance = hitObject.distance; } #endif break; case MasterAudio.RaycastMode.Physics2D: #if PHY2D_ENABLED var castHit2D = Physics2D.Raycast(raycastOrigin, direction, distanceToListener); if (castHit2D.transform != null) { isHit = true; hitPoint = castHit2D.point; hitDistance = castHit2D.distance; } #endif break; } } if (is2DRaycast) { #if PHY2D_ENABLED Physics2D.queriesStartInColliders = oldQueriesStart; Physics2D.queriesHitTriggers = oldRaycastsHitTriggers; #endif } else { #if PHY3D_ENABLED Physics.queriesHitTriggers = oldRaycastsHitTriggers; #endif } if (_maThisFrame.occlusionShowRaycasts) { var endPoint = isHit ? hitPoint : _listenerThisFrame.position; var lineColor = isHit ? Color.red : Color.green; Debug.DrawLine(raycastOrigin, endPoint, lineColor, .1f); } if (!isHit) { // ReSharper disable once PossibleNullReferenceException MasterAudio.RemoveFromBlockedOcclusionSources(GrpVariation.GameObj); ResetToNonOcclusionSetting(); return(true); } MasterAudio.AddToBlockedOcclusionSources(GrpVariation.GameObj); var ratioToEdgeOfSound = hitDistance.Value / VarAudio.maxDistance; var filterFrequency = AudioUtil.GetOcclusionCutoffFrequencyByDistanceRatio(ratioToEdgeOfSound, this); var fadeTime = _maThisFrame.occlusionFreqChangeSeconds; if (fadeTime <= MasterAudio.InnerLoopCheckInterval) // fast, just do it instantly. // ReSharper disable once PossibleNullReferenceException { GrpVariation.LowPassFilter.cutoffFrequency = filterFrequency; return(true); } MasterAudio.GradualOcclusionFreqChange(GrpVariation, fadeTime, filterFrequency); return(true); }
// TODO: Deprecated function //public void CaptureImport() //{ // // Sequence: Called from GelColorImport class, when the gels are processed // // (This is because we need the gel colors before we can assign color values to the imported lights // captureImport.ImportData(); // cuesManager.ImportCues(); //} void Update () { //if (Input.GetKeyDown(KeyCode.P)) //{ // cuesManager.ImportCues(); //} //if (Input.GetKeyDown(KeyCode.O)) //{ // cuesManager.UnsetAllCues(); //} if (Input.GetKeyDown(KeyCode.Equals)) { cuesManager.cuesImport.SerializeCuesData(cuesManager.cuesImport.defaultCuesExportData); } if (Input.GetKeyDown(KeyCode.H)) { if (lightManager.increasedVisibility) { foreach (KeyValuePair<int, GameObject> entry in lightManager.lightIds) { entry.Value.GetComponent<LightFixture>().IncreaseVisibility(false); } lightManager.increasedVisibility = false; } else { foreach (KeyValuePair<int, GameObject> entry in lightManager.lightIds) { entry.Value.GetComponent<LightFixture>().IncreaseVisibility(true); } lightManager.increasedVisibility = true; } } if (Input.GetButtonDown("Fire1")) { // More flexible than explicitly getting MouseButton 0, for VR, etc. if (!EventSystem.current.IsPointerOverGameObject()) { RaycastHit hit; Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition); if (Physics.Raycast(ray, out hit, 200f, layerMask)) { //Debug.Log("Clicked: " + hit.transform.parent.parent.parent.parent.name); if (hit.transform.tag == "Light") { if (hit.transform.GetComponent<LightFixture>() != null) { LightFixture lightFixture = hit.transform.GetComponent<LightFixture>(); SelectLight(lightFixture); } } } else { DeselectAll(); } } else { if (EventSystem.current.IsPointerOverGameObject()) { } else { DeselectAll(); } } } }
private void Shoot() { readyToShoot = false; //Find the exact hit position using a raycast Ray ray = fpsCam.ViewportPointToRay(new Vector3(0.5f, 0.5f, 0)); //Just a ray through the middle of your current view RaycastHit hit; //check if ray hits something Vector3 targetPoint; if (Physics.Raycast(ray, out hit)) targetPoint = hit.point; else targetPoint = ray.GetPoint(75); //Just a point far away from the player //Calculate direction from attackPoint to targetPoint Vector3 directionWithoutSpread = targetPoint - attackPoint.position; //Calculate spread float x = Random.Range(-spread, spread); float y = Random.Range(-spread, spread); //Calculate new direction with spread Vector3 directionWithSpread = directionWithoutSpread + new Vector3(x, y, 0); //Just add spread to last direction //Instantiate bullet/projectile GameObject currentBullet = Instantiate(bullet, attackPoint.position, Quaternion.identity); //store instantiated bullet in currentBullet //Rotate bullet to shoot direction currentBullet.transform.forward = directionWithSpread.normalized; //Add forces to bullet currentBullet.GetComponent<Rigidbody>().AddForce(directionWithSpread.normalized * shootForce, ForceMode.Impulse); currentBullet.GetComponent<Rigidbody>().AddForce(fpsCam.transform.up * upwardForce, ForceMode.Impulse); if(currentBullet.gameObject.CompareTag("Enemy")) { Destroy(currentBullet.gameObject, 3); } if (currentBullet.gameObject.CompareTag("Thing")) { Destroy(currentBullet.gameObject, 3); } //Instantiate muzzle flash, if you have one if (muzzleFlash != null) Instantiate(muzzleFlash, attackPoint.position, Quaternion.identity); bulletsLeft--; bulletsShot++; //Invoke resetShot function (if not already invoked), with your timeBetweenShooting if (allowInvoke) { Invoke("ResetShot", timeBetweenShooting); allowInvoke = false; //Add recoil to player (should only be called once) playerRb.AddForce(-directionWithSpread.normalized * recoilForce, ForceMode.Impulse); } //if more than one bulletsPerTap make sure to repeat shoot function if (bulletsShot < bulletsPerTap && bulletsLeft > 0) Invoke("Shoot", timeBetweenShots); }
//땅에 붙어있는지 유무 private void IsGround() { isGround = Physics.Raycast(transform.position, Vector3.down, capsuleCollider.bounds.extents.y + 0.3f); theCrossHair.JumpingAnimation(!isGround); }
private void MakeRays() { float stepAngleDeg = 360 / numberOfRays; foreach (float j in radii) { for (int i = 0; i < numberOfRays; i++) { Vector3 localRotation = camPos.right * Mathf.Cos(i * stepAngleDeg) * j + camPos.up * Mathf.Sin(i * stepAngleDeg) * j; Vector3 direction = (Quaternion.Euler(localRotation) * camPos.forward).normalized; Ray ray = new Ray(camPos.position, direction); RaycastHit hitInfo; if (Physics.Raycast(ray, out hitInfo, depth, layerMask:mask.value)) { GameObject g = hitInfo.collider.gameObject; if (!objects.Contains(g)) { objects.Add(g); RM.Add(w1 / j * 1 / 1440); } else { RM[objects.IndexOf(g)] += w1 / j * 1 / 1440; } } //Debug.DrawLine(ray.origin, ray.origin+(direction*depth), Color.red); } } foreach (RaycastHit hit in ConeCastExtension.ConeCastAll(physics, camPos.position, r, camPos.forward, d, a, mask)) { float extraValue = 0f; FocusWeight f = hit.collider.gameObject.GetComponent <FocusWeight>(); float metricValue = 0f; if (f != null) { extraValue = f.weight; } if (objects.Contains(hit.collider.gameObject)) { metricValue = RM[objects.IndexOf(hit.collider.gameObject)]; } float value = a1 * metricValue + a2 * Mathf.Exp(-w2 * hit.distance) + a3 * extraValue; if (value > threshold) { hit.collider.gameObject.layer = LayerMask.NameToLayer("Default"); } else { hit.collider.gameObject.layer = LayerMask.NameToLayer("Focus"); foreach (Transform trans in hit.collider.gameObject.GetComponentsInChildren <Transform>(true)) { trans.gameObject.layer = LayerMask.NameToLayer("Focus"); } } } // foreach (GameObject obj in objects) // { // distances.Add(1/Vector3.Magnitude(obj.transform.position - camPos.transform.position)); // } }
void FixedUpdate() { m_isGrounded = false; float terrainHeight = ModTerrainUtil.GetHeight(transform.position.x, transform.position.z); NetManager netManager = Singleton <NetManager> .instance; //Segment3 ray = new Segment3(gameObject.transform.position + new Vector3(0f, 1.0f, 0f), gameObject.transform.position - new Vector3(0, 0.1f, 0)); Vector3 hitPos; Vector3 hitPos2; ushort nodeIndex; ushort segmentIndex; //Need to check fron below up becuse how the way road raycast work Segment3 ray2 = new Segment3(gameObject.transform.position, gameObject.transform.position - new Vector3(0f, 1.0f, 0f)); Segment3 ray = new Segment3(gameObject.transform.position + new Vector3(0f, 1.5f, 0f), gameObject.transform.position + new Vector3(0f, -100f, 0f)); if (NetManager.instance.RayCast(ray, 0f, ItemClass.Service.Road, ItemClass.Service.PublicTransport, ItemClass.SubService.None, ItemClass.SubService.None, ItemClass.Layer.Default, ItemClass.Layer.None, NetNode.Flags.None, NetSegment.Flags.None, out hitPos, out nodeIndex, out segmentIndex) | NetManager.instance.RayCast(ray, 0f, ItemClass.Service.Beautification, ItemClass.Service.Water, ItemClass.SubService.None, ItemClass.SubService.None, ItemClass.Layer.Default, ItemClass.Layer.None, NetNode.Flags.None, NetSegment.Flags.None, out hitPos2, out nodeIndex, out segmentIndex)) { terrainHeight = Mathf.Max(terrainHeight, Mathf.Max(hitPos.y, hitPos2.y)); } if (transform.position.y < terrainHeight + 1 && m_velocity.y <= 0) { transform.position = new Vector3(transform.position.x, terrainHeight + 1 - TERRAIN_HEIGHT_OFFSET, transform.position.z); m_velocity.y = Math.Max(0, m_velocity.y); m_isGrounded = true; } RaycastHit rayHit3; //Move the collider up a bit so it dosen't touch the thing it gonna sweep test aganst m_sweepTestCollider.transform.position = transform.position + Vector3.up * 0.05f; if (m_sweepTestRigidbody.SweepTest(Vector3.down, out rayHit3, 0.1f)) { m_isGrounded = true; m_velocity.y = Math.Max(0, m_velocity.y); } m_sweepTestCollider.transform.position = new Vector3(0, 10000, 0); if (!m_isGrounded && Physics.CheckSphere(transform.position - new Vector3(0, 1, 0), 0.45f)) { m_isGrounded = true; m_velocity.y = Math.Max(0, m_velocity.y); } RaycastHit rayHit2; if (m_rigidBody.SweepTest(Vector3.up, out rayHit2, 0.05f)) //Stops your Y speed when you hit the roof so you fall own directly { m_velocity.y = Math.Min(0, m_velocity.y); } if (PlayerInput.JumpKey.GetKeyDown() && (m_isGrounded || m_hookHit)) { if (m_hookHit) { m_hookHit = false; m_hookLineRender.enabled = false; SendPlayerHookReleased(); } Jump(); } float movementSpeed = PlayerInput.WalkKey.GetKey() ? WALK_SPEED : RUN_SPEED; if (!m_hookHit) { int verticalInput = PlayerInput.MoveForwardsKey.GetKey() ? 1 : PlayerInput.MoveBackwardsKey.GetKey() ? -1 : 0; int horInput = PlayerInput.MoveRightKey.GetKey() ? 1 : PlayerInput.MoveLeftKey.GetKey() ? -1 : 0; Vector3 inputDir = new Vector3(horInput, 0, verticalInput); inputDir.Normalize(); m_velocity += transform.rotation * inputDir * movementSpeed * Time.fixedDeltaTime; m_velocity.x = (m_velocity.x * (1 - GROUND_SLOW)); m_velocity.z = (m_velocity.z * (1 - GROUND_SLOW)); if (!m_isGrounded) { m_velocity.y -= GRAVITY * Time.fixedDeltaTime; //Applys extra gravity becuse the normal one isen't enouch, and don't want to change the global gravity } m_jumpExtraTimer -= Time.fixedDeltaTime; if (PlayerInput.JumpKey.GetKey()) { m_jumpExtraTimer = JUMP_INPUT_EXTRA_TIME; } if (m_jumpExtraTimer > 0 && m_isGrounded) { Jump(); } if (PlayerInput.JumpKey.GetKey() && m_hookHit) { m_hookHit = false; m_hookLineRender.enabled = false; SendPlayerHookReleased(); Jump(); } RaycastHit rayHit; Vector3 newVelocity = m_velocity; for (int i = 0; i < 5; i++) { Vector3 newDelta = newVelocity * Time.fixedDeltaTime; m_sweepTestCollider.transform.position = transform.position + -newDelta.normalized * 0.1f; if (m_sweepTestRigidbody.SweepTest(newDelta.normalized, out rayHit, newDelta.magnitude + 0.1f)) { m_sweepTestCollider.transform.position = transform.position + new Vector3(0, STEP_SIZE, 0) + -newDelta.normalized * 0.1f; if (m_isGrounded && !m_sweepTestRigidbody.SweepTest(newDelta.normalized, out rayHit, newDelta.magnitude + 0.1f)) { float newY = transform.position.y + STEP_SIZE; m_sweepTestCollider.transform.position = new Vector3(transform.position.x + newDelta.x, transform.position.y + STEP_SIZE, transform.position.z + newDelta.z); if (m_sweepTestRigidbody.SweepTest(Vector3.down, out rayHit, STEP_SIZE)) { newY -= rayHit.distance; } m_stepNewPosition = new Vector3(transform.position.x + newDelta.x, newY, transform.position.z + newDelta.z); break; } var distanceToPlane = Vector3.Dot(newDelta, rayHit.normal); Vector3 desiredMotion = (distanceToPlane * rayHit.normal) / Time.fixedDeltaTime; newVelocity -= desiredMotion; newVelocity += rayHit.normal * 0.001f; } m_sweepTestCollider.transform.position = new Vector3(0, -10000, 0); } if (PlayerInput.JumpKey.GetKey() && m_lastJumpTimer <= JUMP_EXTRA_HEIGHT_TIME) { m_velocity.y = JUMP_FORCE; } if (!m_isGrounded) { newVelocity.y = newVelocity.y - newVelocity.y * AIR_Y_SLOW * Time.deltaTime; } m_velocity = newVelocity; m_rigidBody.velocity = m_velocity; } }