I’ve been busy with this for a while, the code I’ve added below is moving objects without any problems, but before that I want to select the object, any help is very important.
I want to select the object first and then move it to the clicked position.`
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.InputSystem;
[RequireComponent(typeof(CharacterController))]
//[RequireComponent(typeof(Rigidbody))]
public class Moved : MonoBehaviour
{
[SerializeField]
private InputAction mouseClickAction;
[SerializeField]
private float playerSpeed = 10f;
[SerializeField]
private float rotationSpeed = 3f;
private Camera mainCamera;
private Coroutine coroutine;
private Vector3 targetPosition;
private CharacterController characterController;
// private Rigidbody rb;
private int groundLayer;
private void Awake()
{
mainCamera = Camera.main;
characterController = GetComponent<CharacterController>();
//rb = GetComponent<Rigidbody>();
groundLayer = LayerMask.NameToLayer("Ground");
gameObject.transform.position = new Vector3(0f, 0f, 0f);
}
private void OnEnable()
{
mouseClickAction.Enable();
mouseClickAction.performed += Move;
}
private void OnDisable()
{
mouseClickAction.performed -= Move;
mouseClickAction.Disable();
}
private void Move(InputAction.CallbackContext context)
{
Ray ray = mainCamera.ScreenPointToRay(Mouse.current.position.ReadValue());
if (Physics.Raycast(ray: ray, hitInfo: out RaycastHit hit) && hit.collider && hit.collider.gameObject.layer.CompareTo(groundLayer) == 0)
{
if (coroutine != null) StopCoroutine(coroutine);
coroutine = StartCoroutine(PlayerMoveTowards(hit.point));
targetPosition = hit.point;
}
}
private IEnumerator PlayerMoveTowards(Vector3 target)
{
float playerDistanceToFloor = transform.position.y - target.y;
target.y += playerDistanceToFloor;
while (Vector3.Distance(transform.position, target) > 0.1f)
{
Vector3 destination = Vector3.MoveTowards(transform.position, target, playerSpeed * Time.deltaTime);
// transform.position = destination;
Vector3 direction = target - transform.position;
Vector3 movement = playerSpeed * Time.deltaTime * direction.normalized;
characterController.Move(movement);
//rb.velocity = direction.normalized * playerSpeed;
transform.rotation = Quaternion.Slerp(transform.rotation, Quaternion.LookRotation(direction.normalized), rotationSpeed * Time.deltaTime);
yield return null;
}
}