Avoiding Obstacles While Moving to a Point Using NavMesh
NavMeshPointMovement.cs
using UnityEngine;
using UnityEngine.AI;
public class NavMeshPointMovement : MonoBehaviour
{
NavMeshAgent agent;
RaycastHit hit;
void Awake()
{
agent = GetComponent<NavMeshAgent>();
}
void Update()
{
if (Input.GetMouseButtonDown(0))
{
if (Physics.Raycast(Camera.main.ScreenPointToRay(Input.mousePosition), out hit, 100, LayerMask.GetMask("Ground")))
{
agent.SetDestination(hit.point);
}
}
}
}
Drawing Connected Straight Lines on a Surface Using Line Renderer
LineCreator.cs
using System.Linq;
using UnityEngine;
public class LineCreator : MonoBehaviour
{
LineRenderer lineRenderer;
RaycastHit hit;
void Awake()
{
lineRenderer = gameObject.AddComponent<LineRenderer>();
lineRenderer.startWidth = 0.1f;
lineRenderer.material = Resources.FindObjectsOfTypeAll<Material>().SingleOrDefault(m => m.name == "Line");
lineRenderer.positionCount = 0;
}
void Update()
{
if (Input.GetMouseButtonDown(0))
{
if (Physics.Raycast(Camera.main.ScreenPointToRay(Input.mousePosition), out hit))
{
AddLinePoints(hit.point + hit.normal.normalized * 0.1f);
}
}
if (Input.GetMouseButtonDown(1))
{
ClearLinePoints();
}
}
void AddLinePoints(Vector3 point)
{
lineRenderer.positionCount++;
lineRenderer.SetPosition(lineRenderer.positionCount-1, point);
}
void ClearLinePoints()
{
lineRenderer.positionCount = 0;
}
}
Moving Player through Collection of Clicked Points on a Surface
ClickedPointsMovement.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ClickedPointsMovement : MonoBehaviour
{
public float speed = 15;
Queue<Vector3> targetPointsQueue = new Queue<Vector3>();
RaycastHit hit;
Camera mainCam;
Coroutine _MoveCR;
int layerMask;
void Awake()
{
mainCam = Camera.main;
layerMask = LayerMask.GetMask("Ground");
}
void Update()
{
if (Input.GetMouseButtonDown(0))
{
if (Physics.Raycast(mainCam.ScreenPointToRay(Input.mousePosition), out hit, 100, layerMask))
{
targetPointsQueue.Enqueue(hit.point);
if (_MoveCR == null)
{
_MoveCR = StartCoroutine(MoveThroughPoints(targetPointsQueue));
}
}
}
}
IEnumerator MoveThroughPoints(Queue<Vector3> points)
{
while (points.Count > 0)
{
Vector3 targetPoint = points.Dequeue();
targetPoint = new Vector3(targetPoint.x, transform.position.y, targetPoint.z);
while (Vector3.Distance(transform.position, targetPoint) > 0.01f)
{
transform.position = Vector3.MoveTowards(transform.position, targetPoint, speed * Time.deltaTime);
yield return null;
}
}
_MoveCR = null;
}
}
Moving Player to a Point Clicked by the Mouse on a Surface
ClickedPointMovement.cs
using System.Collections;
using UnityEngine;
public class ClickedPointMovement : MonoBehaviour
{
public float speed = 30;
RaycastHit hit;
Camera mainCam;
Coroutine _MoveCR;
int layerMask;
void Awake()
{
mainCam = Camera.main;
layerMask = LayerMask.GetMask("Ground");
}
void Update()
{
if (Input.GetMouseButtonDown(0))
{
if (Physics.Raycast(mainCam.ScreenPointToRay(Input.mousePosition), out hit, 100, layerMask))
{
if(_MoveCR != null)
{
StopCoroutine(_MoveCR);
}
_MoveCR = StartCoroutine(MoveToPosition(hit.point));
}
}
}
IEnumerator MoveToPosition(Vector3 targetPoint)
{
targetPoint = new Vector3(targetPoint.x, transform.position.y, targetPoint.z);
while (Vector3.Distance(transform.position, targetPoint) > 0.01f)
{
transform.position = Vector3.MoveTowards(transform.position, targetPoint, speed * Time.deltaTime);
yield return null;
}
}
}
Use of Raycast to detect an object in Unity
RaycastDetection.cs
using UnityEngine;
using UnityEngine.UI;
public class RaycastDetection : MonoBehaviour
{
Ray ray;
RaycastHit raycastHit;
Text textUI;
void Awake()
{
textUI = GameObject.FindObjectOfType<Text>();
}
void Update()
{
ray = new Ray(transform.position, transform.forward);
if(Physics.Raycast(ray, out raycastHit))
{
textUI.text = raycastHit.collider.gameObject.name;
}
else
{
textUI.text = "";
}
}
}
Updating player health using event in Unity
Player.cs
using System;
using UnityEngine;
public class Player : MonoBehaviour
{
public static event Action<int> _HealthUpdateEvent;
int health = 100;
public void GainHealth()
{
health = Mathf.Clamp(health + 10,0,100);
if(_HealthUpdateEvent!=null)
{
_HealthUpdateEvent(health);
}
}
public void LooseHealth()
{
health = Mathf.Clamp(health - 10, 0, 100);
if (_HealthUpdateEvent != null)
{
_HealthUpdateEvent(health);
}
}
}
HealthDisplay.cs
using UnityEngine;
using UnityEngine.UI;
[RequireComponent(typeof(Text))]
public class HealthDisplay : MonoBehaviour
{
Text healthValueText;
void Awake()
{
healthValueText = GetComponent<Text>();
}
void OnEnable()
{
Player._HealthUpdateEvent += UpdateHealth;
}
void OnDisable()
{
Player._HealthUpdateEvent -= UpdateHealth;
}
void UpdateHealth(int value)
{
healthValueText.text = value.ToString("000") + " / 100";
}
}
Correct way to start and stop a Coroutine
CoroutineDemo.cs
using System.Collections;
using UnityEngine;
public class CoroutineDemo : MonoBehaviour
{
IEnumerator coroutine;
void Start()
{
Debug.Log(">>> Coroutine Started. <<<");
coroutine = PintEvery1Sec();
StartCoroutine(coroutine);
}
void Update()
{
if (Input.GetKeyDown(KeyCode.Space))
{
if (coroutine != null)
{
StopCoroutine(coroutine);
coroutine = null;
Debug.Log(">>> Coroutine Stopped. <<<");
}
}
}
IEnumerator PintEvery1Sec()
{
int i = 0;
while (true)
{
i++;
Debug.Log(i);
yield return new WaitForSeconds(1);
}
}
}
A simple timer using Coroutine
SimpleTimer.cs
using System.Collections;
using UnityEngine;
using UnityEngine.UI;
public class SimpleTimer : MonoBehaviour
{
public Text timerTxt;
public Button startTimerBtn;
public Button stopTimerBtn;
IEnumerator _timerCR;
void Awake()
{
startTimerBtn.onClick.AddListener(StartTimerClick);
stopTimerBtn.onClick.AddListener(StopTimerClick);
ResetTimer();
}
#region button clicks
void StartTimerClick()
{
_timerCR = StartTimer();
StartCoroutine(_timerCR);
}
void StopTimerClick()
{
if(_timerCR!=null)
{
StopCoroutine(_timerCR);
_timerCR = null;
}
ResetTimer();
}
#endregion
#region start/reset timer
IEnumerator StartTimer(int timeRemaining = 10)
{
startTimerBtn.interactable = false;
stopTimerBtn.interactable = true;
for (int i = timeRemaining; i > 0; i--)
{
timerTxt.text = i.ToString("00");
yield return new WaitForSeconds(1);
}
ResetTimer();
}
void ResetTimer()
{
startTimerBtn.interactable = true;
stopTimerBtn.interactable = false;
timerTxt.text = "00";
}
#endregion
}
Player movement using character controller based on front facing direction
PlayerMovement.cs
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
CharacterController characterController;
public float speed = 5;
public float turnSpeed = 90;
void Awake()
{
characterController = GetComponent<CharacterController>();
}
void Update()
{
characterController.Move(transform.forward * Input.GetAxis("Vertical") * speed * Time.deltaTime);
transform.Rotate(Vector3.up, Input.GetAxis("Horizontal") * turnSpeed * Time.deltaTime);
}
}
Player simple movement based on input direction
PlayerSimpleMovement.cs
using UnityEngine;
public class PlayerSimpleMovement : MonoBehaviour
{
float h = 0;
float v = 0;
public float speed = 5;
void Update()
{
h = Input.GetAxis("Horizontal");
v = Input.GetAxis("Vertical");
transform.position += new Vector3(h * Time.deltaTime * speed, 0, v * Time.deltaTime * speed);
}
}
Control your camera to look around using mouse
MouseLookAround.cs
using UnityEngine;
public class MouseLookAround : MonoBehaviour
{
float rotationX = 0f;
float rotationY = 0f;
public float sensitivity = 15f;
void Update()
{
rotationY += Input.GetAxis("Mouse X") * sensitivity;
rotationX += Input.GetAxis("Mouse Y") * -1 * sensitivity;
transform.localEulerAngles = new Vector3(rotationX,rotationY,0);
}
}
Improved Script(Smooth Rotation & Sensitivity Axis Control)
using UnityEngine;
public class MouseLookAround : MonoBehaviour
{
float rotationX = 0f;
float rotationY = 0f;
public Vector2 sensitivity = Vector2.one * 360f;
void Update()
{
rotationY += Input.GetAxis("Mouse X") * Time.deltaTime * sensitivity.x;
rotationX += Input.GetAxis("Mouse Y") * Time.deltaTime * -1 * sensitivity.y;
transform.localEulerAngles = new Vector3(rotationX, rotationY, 0);
}
}
Subscribe to:
Comments (Atom)