Is there a way to move a player with forces only if the mouse has changed position?
I am starting a project but for movement we are looking to move the player only based on changes in mouse position, regardless of clicking. Is this even possible? I have coding experience but am new to Unity's API. To be more specific, if the player moves the mouse forward we want the player object to move forward as well, and if the mouse is moved left or right we would like the player to move left or right as well, but we do not want the object to follow the mouse, just check to see if there is a change in mouse position in the x or y and then apply a force to the object in the appropriate direction. I hope that is a bit more clear.
Answer by tinylord202 · Dec 09, 2018 at 03:57 AM
I'm not quite sure what you are asking but, I feel you may want to use a navmesh and a navmesh agent. With the agent you could write a code like this
.
using UnityEngine;
using UnityEngine.AI;
public Class movePlayer : MonoBehavior {
//the part that moves the player
NavmeshAgent agent;
void Start(){
//get the reference to the agent
agent = GetComponent<NavmeshAgent>();
}
void Update (){
//make a raycast from the camera to where the mouse is
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
//see if anything is hit
if(Physics.Raycast(ray, 100, out hit)){
//move the player to where the ray hit
agent.destination = hit.point;
}
}
}
Sorry for the late response, but I am attempting to check your solution but the constructor for " Physics.Raycast() " takes a vector3. Not sure if this was supposed to be a direct example but I have also added some clarification to my question. I am looking into the Nav$$anonymous$$esh and Raycasting atm. Thanks for the response btw.