namespace SmoothMovement
{
public interface IPlayerInput
{
float Acceleration { get; }
}
}
namespace SmoothMovement
{
public interface ISmoothAcceleration
{
float Smooth(float acceleration, float input);
}
}
using UnityEngine;
namespace SmoothMovement
{
public class MobileInput : MonoBehaviour, IPlayerInput
{
public float Acceleration { get; private set; }
[SerializeField] private float _minAcceleration = -1f;
[SerializeField] private float _maxAcceleration = 1f;
[SerializeField] private float _smoothMultiplier = 5f;
[Range(0, 1)] [SerializeField] private float _fadingSpeed = 0.01f;
private ISmoothAcceleration _smoothing;
private void Awake()
{
_smoothing = new SmoothedAcceleration(_minAcceleration, _maxAcceleration, _smoothMultiplier, _fadingSpeed);
}
private void Update()
{
Acceleration = _smoothing.Smooth(Acceleration, Input.acceleration.x);
}
}
}
using UnityEngine;
namespace SmoothMovement
{
public class SmoothedAcceleration : ISmoothAcceleration
{
private readonly float _multiplier;
private readonly float _minValue;
private readonly float _maxValue;
private readonly float _fadingSpeed;
public SmoothedAcceleration(float minValue, float maxValue, float multiplier, float fadeSpeed)
{
_minValue = minValue;
_maxValue = maxValue;
_multiplier = multiplier;
_fadingSpeed = fadeSpeed;
}
public float Smooth(float acceleration, float input)
{
if (input == 0)
{
acceleration = Mathf.Lerp(acceleration, 0, _fadingSpeed);
return acceleration;
}
acceleration += input * _multiplier * Time.deltaTime;
acceleration = Mathf.Clamp(acceleration, _minValue, _maxValue);
return acceleration;
}
}
}
using UnityEngine;
namespace SmoothMovement
{
public class TestMovement : MonoBehaviour
{
[SerializeField] private MonoBehaviour _input = null;
[SerializeField] private float _speed = 10f;
private IPlayerInput Input => (IPlayerInput)_input;
private void OnValidate()
{
if (_input is IPlayerInput) return;
Debug.LogError($"{nameof(_input)} should implement {nameof(IPlayerInput)}");
_input = null;
}
private void FixedUpdate()
{
Move(Input.Acceleration);
}
private void Move(float direction)
{
if (direction == 0) return;
var position = transform.position;
position.x += direction * _speed * Time.deltaTime;
transform.position = position;
}
}
}
using System.Collections;
using UnityEngine;
using UnityEngine.UI;
public class SliderFilling : MonoBehaviour
{
[SerializeField] private Slider _slider = null;
[SerializeField] private float _fillTime = 3f;
private void Update()
{
if (Input.GetKeyDown(KeyCode.Space))
{
StartCoroutine(FillValue(0.5f));
}
}
private IEnumerator FillValue(float value)
{
var estimateTime = 0f;
while(estimateTime < _fillTime)
{
estimateTime += Time.deltaTime;
_slider.value = Mathf.Lerp(0, value, estimateTime / _fillTime);
yield return null;
}
}
}
public class KeyboardInput : MonoBehaviour, IPlayerInput
{
public event Action ActionButtonPressed;
private void Update()
{
if (Input.GetKeyDown(KeyCode.F))
{
ActionButtonPressed?.Invoke();
}
}
}
public interface IPlayerInput
{
public event Action ActionButtonPressed;
}
[RequireComponent(typeof(Collider2D))]
public class DialogueTrigger : MonoBehaviour
{
[SerializeField] private KeyboardInput _input;
private void OnTriggerEnter2D(Collider2D collision)
{
if (collision.TryGetComponent(out Player player))
{
_input.ActionButtonPressed += StartDialogue;
}
}
private void OnTriggerExit2D(Collider2D collision)
{
if (collision.TryGetComponent(out Player player))
{
_input.ActionButtonPressed -= StartDialogue;
EndDialogue();
}
}
private void StartDialogue()
{
Debug.Log("DialogueStarted");
}
private void EndDialogue()
{
Debug.Log("DialogueEnded");
}
}
var distance = (point.position - transform.position).magnitude;
public class Example : MonoBehaviour
{
[SerializeField] private Transform _pointA, _pointB = null;
[SerializeField] private float _speed = 10f;
[SerializeField] private float _closeDistance = 0.2f;
private Transform _currentPoint;
private void Start()
{
_currentPoint = _pointA;
}
private void FixedUpdate()
{
MoveTo(_currentPoint.position);
}
private void MoveTo(Vector3 position)
{
var nextPosition = transform.position;
var delta = (position - transform.position).normalized;
delta *= _speed * Time.deltaTime;
nextPosition += delta;
transform.position = nextPosition;
UpdatePoint();
}
private void UpdatePoint()
{
var distance = (_currentPoint.position - transform.position).magnitude;
if (distance <= _closeDistance)
{
SwitchPoint();
}
}
private void SwitchPoint()
{
_currentPoint = _currentPoint == _pointA ? _pointB : _pointA;
}
}
var ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, out RaycastHit hit, Mathf.Infinity))
{
Debug.DrawRay(hit.point, hit.normal * 10, Color.red, 10f);
}
public interface IButton
{
public void OnClick();
}
public class YellowButton : IButton
{
public void OnClick()
{
Debug.Log("Yellow");
}
}
public class Example : MonoBehaviour
{
private void Update()
{
if (Input.GetMouseButtonDown(0))
{
var ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, out RaycastHit hit, Mathf.Infinity))
{
if(hit.transform.TryGetComponent(out IButton button))
{
button.OnClick();
}
}
}
}
}
public class Button : MonoBehaviour
{
public event Action ButtonPressed;
private void OnMouseDown()
{
ButtonPressed?.Invoke();
}
}
public class ButtonHandler : MonoBehaviour
{
[SerializeField] private Button _button;
private void OnEnable()
{
_button.ButtonPressed += DoStuff;
}
private void OnDisable()
{
_button.ButtonPressed -= DoStuff;
}
private void DoStuff()
{
}
}
private void OnTriggerEnter(Collider other)
{
if (other.TryGetComponent(out Player player))
{
PlayerInput.ActionButtonPressed += DoStuff;
}
}
private void OnTriggerExit(Collider other)
{
if (other.TryGetComponent(out Player player))
{
PlayerInput.ActionButtonPressed -= DoStuff;
}
}
private void DoStuff()
{
//Do stuff
}
public class PlayerInput : MonoBehaviour
{
public static event Action ActionButtonPressed;
private void Update()
{
if (Input.GetKeyDown(KeyCode.F))
{
ActionButtonPressed?.Invoke();
}
}
}
[SerializeField] private Slider _slider;
private void OnEnable()
{
_slider.onValueChanged.AddListener(ChangeVolume);
}
private void OnDisable()
{
_slider.onValueChanged.RemoveListener(ChangeVolume);
}
private void ChangeVolume(float amount)
{
//изменить громкость на значение amount
}
using UnityEngine;
namespace Assets.Scripts.Rotation
{
[RequireComponent(typeof(Rigidbody2D))] // Нужен, чтобы компонент Rigidbody2D всегда был на объекте, к которому прикреплен данный скрипт
public class Player : MonoBehaviour
{
[SerializeField] private float _maxSpeed; //[SerializeField] позволяет видеть private поля в инспекторе
[SerializeField] private float _speed;
[Range(0f, 1f)]
[SerializeField] private float _slowDownSpeed; //Range ограничивает между 0 и 1 в данном случае
[SerializeField] private Gun _gun;
private Vector2 _movementDirection;
private Rigidbody2D _rb;
private void Start()
{
_rb = GetComponent<Rigidbody2D>(); // Получаем компонент, если получаете компонент таким образом, обязательно нужно делать [RequireComponent(typeof(НазваниеКомпонента))]
}
private void Update()
{
var horizontal = Input.GetAxis("Horizontal");
var vertical = Input.GetAxis("Vertical");
_movementDirection = new Vector2(horizontal, vertical);
}
private void FixedUpdate() // все действия с физикой в FixedUpdate
{
if (_movementDirection == Vector2.zero) SlowDown(_slowDownSpeed);
Move(_movementDirection, _speed);
Flip();
}
private void Flip()
{
var vector = Camera.main.ScreenToWorldPoint(Input.mousePosition) - transform.position; //берем вектор направления от нашей позиции до позиции мыши в мировых координатах
if (vector.x < 0) transform.eulerAngles = new Vector3(0, 180); // Если он левее, то поворачиваем объект налево
if (vector.x >= 0) transform.eulerAngles = new Vector2(0, 0);// или направо, если он правее
_gun.Flip(vector.x);// поворачиваем оружие
}
private void Move(Vector2 direction, float speed)
{
var velocity = _rb.velocity;
var x = velocity.x + direction.x * speed;// определяем новую скорость
var y = velocity.y + direction.y * speed;
velocity.x = Mathf.Clamp(x, -_maxSpeed, _maxSpeed); //ограничиваем скорость
velocity.y = Mathf.Clamp(y, -_maxSpeed, _maxSpeed);
_rb.velocity = velocity; // присваиваем скорость
}
private void SlowDown(float speed) // замедляем объект
{
var velocity = _rb.velocity;
velocity.x = Mathf.Lerp(velocity.x, 0, speed);
velocity.y = Mathf.Lerp(_rb.velocity.y, 0, speed);
_rb.velocity = velocity;
}
}
}
using UnityEngine;
namespace Assets.Scripts.Rotation
{
[RequireComponent(typeof(SpriteRenderer))]
public class Gun : MonoBehaviour
{
private SpriteRenderer _spriteRenderer;
private void Start()
{
_spriteRenderer = GetComponent<SpriteRenderer>();
}
private void Update()
{
var difference = Camera.main.ScreenToWorldPoint(Input.mousePosition) - transform.position;
var rotation = Mathf.Atan2(difference.y, difference.x) * Mathf.Rad2Deg;
transform.rotation = Quaternion.Euler(0f, 0f, rotation); // ваш код поворота оружия
}
public void Flip(float direction)
{
_spriteRenderer.flipY = direction < 0; // отражаем спрайт по оси Y в зависимости от того, куда смотрит персонаж
}
}
}
new Color(1f, 1f, 1f, 0.5f)
будет полупрозрачный спрайт. При входе в триггер - уменьшаем альфа канал, при выходе увеличиваем. Mathf.Lerp(-80, 0, volume)
замените на просто volume. using System.Collections;
using UnityEngine;
public class Fire : MonoBehaviour
{
private void Start()
{
StartCoroutine(Burn(5f, 1f));
}
private IEnumerator Burn(float time, float damageInterval)
{
while (time > 0)
{
time -= damageInterval;
Debug.Log("ApplyDamage");
yield return new WaitForSeconds(damageInterval);
}
yield break;
}
}
using UnityEngine;
[RequireComponent(typeof(Rigidbody2D))]
public class Bird : MonoBehaviour
{
[SerializeField] private float _speed;
[SerializeField] private float _jumpSpeed;
private Rigidbody2D _rb;
private void Start()
{
_rb = GetComponent<Rigidbody2D>();
}
private void Update()
{
Move();
if (Input.GetKeyDown(KeyCode.Space))
{
Jump();
}
}
private void Jump()
{
var velocity = _rb.velocity;
velocity.y = _jumpSpeed;
_rb.velocity = velocity;
}
private void Move()
{
var velocity = _rb.velocity;
velocity.x = _speed;
_rb.velocity = velocity;
}
}
public class Particles : MonoBehaviour
{
[SerializeField] private ParticleSystem _particle;
private void FixedUpdate()
{
MoveParticles();
}
private void MoveParticles()
{
var position = _particle.transform.position;
position.x = transform.position.x;
_particle.transform.position = position;
}
}