private void Grab() { Vector2 direction = Facing == Facing.right ? Vector2.right : Vector2.left; List <RaycastHit2D> hits = new List <RaycastHit2D>(); Vector2 origin = new Vector2(transform.position.x, transform.position.y - 0.5f); Debug.DrawRay(origin, direction * grabRange, Color.red, 3f); Physics2D.Raycast(origin, direction, grabFilter, hits, grabRange); if (hits.Count > 0) { ICanThrow grabbed = hits.Select(h => h.collider.gameObject.GetComponent <ICanThrow>()) .Where(g => g != null) .ToArray() .FirstOrDefault(); if (grabbed != null) { grabbed.Transform.SetParent(transform); grabbed.Transform.localPosition = Vector2.zero; grabbed.RigidBody.isKinematic = true; throwable = grabbed; } } }
private void Throw() { if (throwable.Transform.IsChildOf(transform)) { throwable.Transform.SetParent(transform.parent); } int xDir = Facing == Facing.right ? 1 : -1; Vector2 force = new Vector2(xDir * 0.5f * throwStrength, throwStrength); throwable.RigidBody.isKinematic = false; throwable.RigidBody.AddForce(force, ForceMode2D.Impulse); throwable = null; }
private void Drop() { if (throwable != null) { if (throwable.Transform.IsChildOf(transform)) { throwable.Transform.SetParent(transform.parent); } throwable.RigidBody.gravityScale = 1; var backwards = Facing == Facing.right ? Vector2.left : Vector2.right; throwable.RigidBody.AddForce(backwards, ForceMode2D.Impulse); throwable = null; } }
/** * Shoot the target position */ public override bool Throw(Func <Vector3> GetTargetPosition) { if (!base.Throw(GetTargetPosition)) { return(false); } ICanThrow thrower = (ICanThrow)_focuser; string fctPeriodicName = "GrenadeThrowing"; FunctionPeriodic.Create( () => { _isThrown = true; transform.SetParent(null); Rigidbody rigidbody = gameObject.AddComponent <Rigidbody>(); rigidbody.mass = _DEFAULT_MASS; rigidbody.interpolation = RigidbodyInterpolation.Interpolate; rigidbody.collisionDetectionMode = CollisionDetectionMode.Discrete; rigidbody.AddForce((GetTargetPosition() - transform.position + (Vector3.up) * 10f).normalized * _impulseForce, ForceMode.Impulse); if (_focuser is Entity e) { e.GetInventory().Remove(this); e.Unequip(this); } // Trigger throw sound SoundManager.PlayThrowSound(transform.position, .6f); }, fctPeriodicName, 0f, 0f, () => { Destroy(GameObject.Find(fctPeriodicName)); } ); return(true); }