Snippets Collections
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

namespace TarodevController
{
    public struct FrameInput
    {
        public float X;
        public bool JumpDown;
        public bool JumpUp;
    }

    public interface IPlayerController
    {
        public Vector3 Velocity { get; }
        public FrameInput Input { get; }
        public bool JumpingThisFrame { get; }
        public bool LandingThisFrame { get; }
        public Vector3 RawMovement { get; }
        public bool Grounded { get; }
    }

    public struct RayRange
    {
        public RayRange(float x1, float y1, float x2, float y2, Vector2 dir)
        {
            Start = new Vector2(x1, y1);
            End = new Vector2(x2, y2);
            Dir = dir;
        }

        public readonly Vector2 Start, End, Dir;
    }
}
using System.Collections.Generic;
using System.Linq;
using UnityEngine;

namespace TarodevController
{
    /// <summary>
    /// Hey!
    /// Tarodev here. I built this controller as there was a severe lack of quality & free 2D controllers out there.
    /// Right now it only contains movement and jumping, but it should be pretty easy to expand... I may even do it myself
    /// if there's enough interest. You can play and compete for best times here: https://tarodev.itch.io/
    /// If you hve any questions or would like to brag about your score, come to discord: https://discord.gg/GqeHHnhHpz
    /// </summary>
    public class PlayerController : MonoBehaviour, IPlayerController
    {
        // Public for external hooks
        public Vector3 Velocity { get; private set; }
        public FrameInput Input { get; private set; }
        public bool JumpingThisFrame { get; private set; }
        public bool LandingThisFrame { get; private set; }
        public Vector3 RawMovement { get; private set; }
        public bool Grounded => _colDown;

        private Vector3 _lastPosition;
        private float _currentHorizontalSpeed, _currentVerticalSpeed;

        // This is horrible, but for some reason colliders are not fully established when update starts...
        private bool _active;
        void Awake() => Invoke(nameof(Activate), 0.5f);
        void Activate() => _active = true;

        private void Update()
        {
            if (!_active) return;
            // Calculate velocity
            Velocity = (transform.position - _lastPosition) / Time.deltaTime;
            _lastPosition = transform.position;

            GatherInput();
            RunCollisionChecks();

            CalculateWalk(); // Horizontal movement
            CalculateJumpApex(); // Affects fall speed, so calculate before gravity
            CalculateGravity(); // Vertical movement
            CalculateJump(); // Possibly overrides vertical

            MoveCharacter(); // Actually perform the axis movement
        }


        #region Gather Input

        private void GatherInput()
        {
            Input = new FrameInput
            {
                JumpDown = UnityEngine.Input.GetButtonDown("Jump"),
                JumpUp = UnityEngine.Input.GetButtonUp("Jump"),
                X = UnityEngine.Input.GetAxisRaw("Horizontal")
            };
            if (Input.JumpDown)
            {
                _lastJumpPressed = Time.time;
            }
        }

        #endregion

        #region Collisions

        [Header("COLLISION")][SerializeField] private Bounds _characterBounds;
        [SerializeField] private LayerMask _groundLayer;
        [SerializeField] private int _detectorCount = 3;
        [SerializeField] private float _detectionRayLength = 0.1f;
        [SerializeField][Range(0.1f, 0.3f)] private float _rayBuffer = 0.1f; // Prevents side detectors hitting the ground

        private RayRange _raysUp, _raysRight, _raysDown, _raysLeft;
        private bool _colUp, _colRight, _colDown, _colLeft;

        private float _timeLeftGrounded;

        // We use these raycast checks for pre-collision information
        private void RunCollisionChecks()
        {
            // Generate ray ranges. 
            CalculateRayRanged();

            // Ground
            LandingThisFrame = false;
            var groundedCheck = RunDetection(_raysDown);
            if (_colDown && !groundedCheck) _timeLeftGrounded = Time.time; // Only trigger when first leaving
            else if (!_colDown && groundedCheck)
            {
                _coyoteUsable = true; // Only trigger when first touching
                LandingThisFrame = true;
            }

            _colDown = groundedCheck;

            // The rest
            _colUp = RunDetection(_raysUp);
            _colLeft = RunDetection(_raysLeft);
            _colRight = RunDetection(_raysRight);

            bool RunDetection(RayRange range)
            {
                return EvaluateRayPositions(range).Any(point => Physics2D.Raycast(point, range.Dir, _detectionRayLength, _groundLayer));
            }
        }

        private void CalculateRayRanged()
        {
            // This is crying out for some kind of refactor. 
            var b = new Bounds(transform.position + _characterBounds.center, _characterBounds.size);

            _raysDown = new RayRange(b.min.x + _rayBuffer, b.min.y, b.max.x - _rayBuffer, b.min.y, Vector2.down);
            _raysUp = new RayRange(b.min.x + _rayBuffer, b.max.y, b.max.x - _rayBuffer, b.max.y, Vector2.up);
            _raysLeft = new RayRange(b.min.x, b.min.y + _rayBuffer, b.min.x, b.max.y - _rayBuffer, Vector2.left);
            _raysRight = new RayRange(b.max.x, b.min.y + _rayBuffer, b.max.x, b.max.y - _rayBuffer, Vector2.right);
        }


        private IEnumerable<Vector2> EvaluateRayPositions(RayRange range)
        {
            for (var i = 0; i < _detectorCount; i++)
            {
                var t = (float)i / (_detectorCount - 1);
                yield return Vector2.Lerp(range.Start, range.End, t);
            }
        }

        private void OnDrawGizmos()
        {
            // Bounds
            Gizmos.color = Color.yellow;
            Gizmos.DrawWireCube(transform.position + _characterBounds.center, _characterBounds.size);

            // Rays
            if (!Application.isPlaying)
            {
                CalculateRayRanged();
                Gizmos.color = Color.blue;
                foreach (var range in new List<RayRange> { _raysUp, _raysRight, _raysDown, _raysLeft })
                {
                    foreach (var point in EvaluateRayPositions(range))
                    {
                        Gizmos.DrawRay(point, range.Dir * _detectionRayLength);
                    }
                }
            }

            if (!Application.isPlaying) return;

            // Draw the future position. Handy for visualizing gravity
            Gizmos.color = Color.red;
            var move = new Vector3(_currentHorizontalSpeed, _currentVerticalSpeed) * Time.deltaTime;
            Gizmos.DrawWireCube(transform.position + _characterBounds.center + move, _characterBounds.size);
        }

        #endregion


        #region Walk

        [Header("WALKING")][SerializeField] private float _acceleration = 90;
        [SerializeField] private float _moveClamp = 13;
        [SerializeField] private float _deAcceleration = 60f;
        [SerializeField] private float _apexBonus = 2;

        private void CalculateWalk()
        {
            if (Input.X != 0)
            {
                // Set horizontal move speed
                _currentHorizontalSpeed += Input.X * _acceleration * Time.deltaTime;

                // clamped by max frame movement
                _currentHorizontalSpeed = Mathf.Clamp(_currentHorizontalSpeed, -_moveClamp, _moveClamp);

                // Apply bonus at the apex of a jump
                var apexBonus = Mathf.Sign(Input.X) * _apexBonus * _apexPoint;
                _currentHorizontalSpeed += apexBonus * Time.deltaTime;
            }
            else
            {
                // No input. Let's slow the character down
                _currentHorizontalSpeed = Mathf.MoveTowards(_currentHorizontalSpeed, 0, _deAcceleration * Time.deltaTime);
            }

            if (_currentHorizontalSpeed > 0 && _colRight || _currentHorizontalSpeed < 0 && _colLeft)
            {
                // Don't walk through walls
                _currentHorizontalSpeed = 0;
            }
        }

        #endregion

        #region Gravity

        [Header("GRAVITY")][SerializeField] private float _fallClamp = -40f;
        [SerializeField] private float _minFallSpeed = 80f;
        [SerializeField] private float _maxFallSpeed = 120f;
        private float _fallSpeed;

        private void CalculateGravity()
        {
            if (_colDown)
            {
                // Move out of the ground
                if (_currentVerticalSpeed < 0) _currentVerticalSpeed = 0;
            }
            else
            {
                // Add downward force while ascending if we ended the jump early
                var fallSpeed = _endedJumpEarly && _currentVerticalSpeed > 0 ? _fallSpeed * _jumpEndEarlyGravityModifier : _fallSpeed;

                // Fall
                _currentVerticalSpeed -= fallSpeed * Time.deltaTime;

                // Clamp
                if (_currentVerticalSpeed < _fallClamp) _currentVerticalSpeed = _fallClamp;
            }
        }

        #endregion

        #region Jump

        [Header("JUMPING")][SerializeField] private float _jumpHeight = 30;
        [SerializeField] private float _jumpApexThreshold = 10f;
        [SerializeField] private float _coyoteTimeThreshold = 0.1f;
        [SerializeField] private float _jumpBuffer = 0.1f;
        [SerializeField] private float _jumpEndEarlyGravityModifier = 3;
        private bool _coyoteUsable;
        private bool _endedJumpEarly = true;
        private float _apexPoint; // Becomes 1 at the apex of a jump
        private float _lastJumpPressed;
        private bool CanUseCoyote => _coyoteUsable && !_colDown && _timeLeftGrounded + _coyoteTimeThreshold > Time.time;
        private bool HasBufferedJump => _colDown && _lastJumpPressed + _jumpBuffer > Time.time;

        private void CalculateJumpApex()
        {
            if (!_colDown)
            {
                // Gets stronger the closer to the top of the jump
                _apexPoint = Mathf.InverseLerp(_jumpApexThreshold, 0, Mathf.Abs(Velocity.y));
                _fallSpeed = Mathf.Lerp(_minFallSpeed, _maxFallSpeed, _apexPoint);
            }
            else
            {
                _apexPoint = 0;
            }
        }

        private void CalculateJump()
        {
            // Jump if: grounded or within coyote threshold || sufficient jump buffer
            if (Input.JumpDown && CanUseCoyote || HasBufferedJump)
            {
                _currentVerticalSpeed = _jumpHeight;
                _endedJumpEarly = false;
                _coyoteUsable = false;
                _timeLeftGrounded = float.MinValue;
                JumpingThisFrame = true;
            }
            else
            {
                JumpingThisFrame = false;
            }

            // End the jump early if button released
            if (!_colDown && Input.JumpUp && !_endedJumpEarly && Velocity.y > 0)
            {
                // _currentVerticalSpeed = 0;
                _endedJumpEarly = true;
            }

            if (_colUp)
            {
                if (_currentVerticalSpeed > 0) _currentVerticalSpeed = 0;
            }
        }

        #endregion

        #region Move

        [Header("MOVE")]
        [SerializeField, Tooltip("Raising this value increases collision accuracy at the cost of performance.")]
        private int _freeColliderIterations = 10;

        // We cast our bounds before moving to avoid future collisions
        private void MoveCharacter()
        {
            var pos = transform.position + _characterBounds.center;
            RawMovement = new Vector3(_currentHorizontalSpeed, _currentVerticalSpeed); // Used externally
            var move = RawMovement * Time.deltaTime;
            var furthestPoint = pos + move;

            // check furthest movement. If nothing hit, move and don't do extra checks
            var hit = Physics2D.OverlapBox(furthestPoint, _characterBounds.size, 0, _groundLayer);
            if (!hit)
            {
                transform.position += move;
                return;
            }

            // otherwise increment away from current pos; see what closest position we can move to
            var positionToMoveTo = transform.position;
            for (int i = 1; i < _freeColliderIterations; i++)
            {
                // increment to check all but furthestPoint - we did that already
                var t = (float)i / _freeColliderIterations;
                var posToTry = Vector2.Lerp(pos, furthestPoint, t);

                if (Physics2D.OverlapBox(posToTry, _characterBounds.size, 0, _groundLayer))
                {
                    transform.position = positionToMoveTo;

                    // We've landed on a corner or hit our head on a ledge. Nudge the player gently
                    if (i == 1)
                    {
                        if (_currentVerticalSpeed < 0) _currentVerticalSpeed = 0;
                        var dir = transform.position - hit.transform.position;
                        transform.position += dir.normalized * move.magnitude;
                    }

                    return;
                }

                positionToMoveTo = posToTry;
            }
        }

        #endregion
    }
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class AiShootBall : MonoBehaviour
{
    [SerializeField] Rigidbody soccerRb;

    [SerializeField] float force;

    [SerializeField] Transform target;

    [SerializeField] float curveStartForce;

    float timeToReachDestination;

    bool addCurve=false;

    float timeRemaining;
    // Start is called before the first frame update
    void Start()
    {
        Invoke("ShootBall", 2f);
        //ShootBall();
    }
    
    public void ShootBall()
    {
        //this will get the direction to reach the desitination
        Vector3 dir = target.position - transform.position;
        //then we normalize the value
        dir.Normalize();

        //way of discovering the time it will take to reach destination
        float distance = Vector3.Distance(target.position, transform.position);

        //this will get the time to reach the destination
        timeToReachDestination = TimeBetweenObjects(distance, force);

        //float forceNecessary = ForceNeededToReachDestination(distance, timeToReachDestination);

        //this will tell the code to add curve
        addCurve = true;
        //this will store the time remaining to add curve
        timeRemaining = timeToReachDestination;

        //we add the velocity to the rb
        soccerRb.velocity = dir * force;

        //this will add the initial curve force, so that we then add curve to the opossite direction
        soccerRb.velocity += new Vector3(-curveStartForce, 0, 0);
    }

    private void Update()
    {
        //if we are adding a curve, we decrease the countdown
        if (addCurve)
            timeRemaining -= Time.deltaTime;
    }

    private void FixedUpdate()
    {
        if (addCurve && timeRemaining > 0)
        {
            soccerRb.AddForce(new Vector3((curveStartForce + curveStartForce) / timeToReachDestination * Time.fixedDeltaTime, 0, 0), ForceMode.VelocityChange);   
        }
        //if the time has ended we tell the code to stop adding curve and we reset the curve timer
        else
        {
            addCurve = false;
            timeRemaining = 0;
        }
        
    }

    //this will find the time it will take to reach destination
    float TimeBetweenObjects(float distance, float force)
    {
        float timeBetweenObjects = distance / force;
        Debug.Log("Distance: " + distance + " time to reach: " + timeBetweenObjects + " force " + force);
        return timeBetweenObjects;
    }

    //this will find the force necessary to reach destinatiion
    float ForceNeededToReachDestination(float distance, float timeBetweenObjects)
    {
        //way of discovering force necessary to reach destination at seconds
        float forceNeeded = distance / timeBetweenObjects;
        Debug.Log("Force needed : " + forceNeeded);
        return forceNeeded;
    }
}
 //this will store the initial posityion of the joystick, so it returns to its position when we dont click the screen
    private Vector3 initPosOfJoystick;
    //this will store the transform of joystick
    public RectTransform joystick;

    [SerializeField]
    //this will store the canvas 
    Canvas canvas;

    [SerializeField]
    //this will store the limit of the movement of the joystick
    float limitOfJoystick;

    //this will be true if we are dragging the joystick, we need this, so that we only start moving the joystick when we have clicked it, and not outside of it
    bool amIDragging = false;

    private void Start()
    {
        //get the initial position of the joystick
        initPosOfJoystick = joystick.position;
    }

    // Update is called once per frame
    void Update()
    {
        
        //if the mouse is clicking
        if(Input.GetMouseButton(0))
        {
            //this will store the movepos of the mouse
            Vector2 movePos;
            //get the mouse position on the canvas
            RectTransformUtility.ScreenPointToLocalPointInRectangle(
                canvas.transform as RectTransform,
                Input.mousePosition, canvas.worldCamera,
                out movePos);

            

            //if the distance between the mouse and the 
            if (Vector3.Distance(canvas.transform.TransformPoint(movePos), initPosOfJoystick) < limitOfJoystick)
            {
                //move the joystick to where the mouse is 
                joystick.position = canvas.transform.TransformPoint(movePos);
                amIDragging = true;
            }
                
            //if we are not inside the joystick space, we need to move the joystick to where the mouse is pointing within the limit of the joystick movement
            //and we have started dragging this joystick, we can move him even tho the mouse pos is outside the joystick
            else if(amIDragging==true)
            {
                //this will get the offset from the mouse position and the initial joystick position
                Vector3 offset = canvas.transform.TransformPoint(movePos) - initPosOfJoystick;
                //this will move the mouse within the limitis of the joystick space
                joystick.position = initPosOfJoystick + Vector3.ClampMagnitude(offset, limitOfJoystick);
            }
                
        }
        //if we are not clicking the mouse / touchscreen e move the joystick to its initial position
        else
        {
            //move the joystick to its init pos
            joystick.position = initPosOfJoystick;
            //tell the code that we are no longer dragging
            amIDragging = false;
        }
            
        
    }
using Photon.Pun;
using UnityEngine;

namespace PhotonTutorial.Weapons
{
    public class Weapon : MonoBehaviourPun
    {
        //this will store how fast the bullet moves
        [SerializeField] private float projectileSpeed = 5f;
        //this will store the projectile that is going to be shooted from the gun
        [SerializeField] private GameObject projectile = null;
        //this will store where the bullets will spawn
        [SerializeField] private Transform spawnPoint = null;

        private void Update()
        {
            //if this is my photon view (if this is my character and not any other players character) call the function that thakes input
            if (photonView.IsMine)
            {
                //call the function that handles the input
                TakeInput();
            }
        }

        private void TakeInput()
        {
            //if the player hasnt clicked mouse button, leave this function
            if(!Input.GetMouseButtonDown(0)) { return; }
            //since the user clicked the shooting button, call the function fire projectile, that is going to spawn a bullet on every player pc
            FireProjectile();
        }

    
        private void FireProjectile()
        {
            //this is going to spawn the bullet on every computer (since we are using PunRPC)
            GameObject projectileInstance = PhotonNetwork.Instantiate(projectile.name, spawnPoint.position, spawnPoint.rotation);
            //this is going to add velocity to where the spawn bullet is facing, in this case is from the spawn point
            projectileInstance.GetComponent<Rigidbody>().velocity = projectileInstance.transform.forward * projectileSpeed;
        }
    }
}
export JAVA_HOME=/Users/kenmiya/workspace/Unity/2021.1.1f1/PlaybackEngines/AndroidPlayer/OpenJDK/jre
echo $JAVA_HOME
export PATH=$JAVA_HOME/bin:$PATH
echo $PATH
    public float movementSpeed;

    public Rigidbody2D rb;



    float mx;



    private void Update()
    {

        mx = Input.GetAxisRaw("Horizontal");

    }



    private void FixedUpdate()
    {

        Vector2 movement = new Vector2(mx * movementSpeed, rb.velocity.y);



        rb.velocity = movement;



    }
if (isExplosion) {
    foreach (GameObject enemy in units) {
        float distanceToEnemy = Vector3.Distance (transform.position, enemy.transform.position);
        if (distanceToEnemy <= explosionRadius) {
            Unit unit = enemy.GetComponent<Unit> ();
            float proximity = (transform.position - enemy.transform.position).magnitude;
            float effect = 1 - (proximity / explosionRadius);
            unit.TakeDamage ((int) (damage * effect));
            if (enemy.GetComponent<Setup> ().currentHealth <= 0) {
                GameObject explosionDestroy = Instantiate (enemy.GetComponent<Setup> ().explosionDestroy, enemy.transform.position, Quaternion.identity);
                Destroy (explosionDestroy, 1);
                Destroy (enemy);
            }
        }
    }
}
star

Sat Jul 02 2022 20:26:43 GMT+0000 (UTC) https://www.youtube.com/watch?v=3sWTzMsmdx8

#c# #unity #physics #2d #platform
star

Wed May 04 2022 13:55:40 GMT+0000 (UTC) https://localcoder.org/position-ui-to-mouse-position-make-tooltip-panel-follow-cursor

#c# #unity
star

Tue Apr 12 2022 02:19:39 GMT+0000 (UTC) https://www.youtube.com/watch?v=NA5rO8j21JY&list=PLS6sInD7ThM0nJcyLfxgP9fnHKoQMJu-v&index=5

#c# #unity #unity #photon
star

Sun Jun 20 2021 02:03:51 GMT+0000 (UTC)

#shell #unity

Save snippets that work with our extensions

Available in the Chrome Web Store Get Firefox Add-on Get VS Code extension