- Home /
This question was
closed Apr 12, 2020 at 01:36 PM by
JustAbhi for the following reason:
Found the right answer.
Question by
JustAbhi · Apr 09, 2020 at 12:12 PM ·
c#programmingfps controllerfpscontrollerfpswalker
fps player controller using rigidbody without character controller?
Edit:I think the question might have been misunderstood so this is just to clarify. I have a gameobject which is followed by my main camera. I can look around with my mouse but cannot move in the direction my mouse is facing(fps game) Any help will be very useful. Found the answer..
public Transform plr,cmr;
public Rigidbody rb;
public float xclamp=0f,speed=0f,mousespd=0f;
void Update(){
x = Input.GetAxis("Horizontal") * speed;
y = Input.GetAxis("Vertical") * speed;
Vector3 mov = new Vector3(x, 0f, y);
mov = transform.TransformDirection(mov);
rb.AddForce(mov);
float mousex = Input.GetAxis("Mouse X") * mousespd;
float mousey = Input.GetAxis("Mouse Y") * mousespd;
xclamp -= mousey;
Vector3 rotplr = plr.transform.rotation.eulerAngles;
Vector3 rotcmr = cmr.transform.rotation.eulerAngles;
rotcmr.x -= mousey;
rotcmr.z = 0;
rotplr.y += mousex;
if (xclamp > 90)
{
xclamp = 90;
rotcmr.x = 90;
}
else if (xclamp < -90f)
{
xclamp = -90;
rotcmr.x = 270;
}
cmr.rotation = Quaternion.Euler(rotcmr);
plr.rotation = Quaternion.Euler(rotplr);
}
Comment
Best Answer
Answer by azerty0220pl · Apr 09, 2020 at 01:04 PM
Hello @JustAbhi Something like this should work:
//your player and camera gameObjects
public GameObject player;
public GameObject camera;
//Mouse input will be stored in x and y. Rotation speed (kind of sesitivity)
//is stored in speed, public, so you can change it in the inspector.
//By default it will be null (zero), so it will not work until you change it.
float x;
float y;
public float speed;
void Update()
{
//Read mouse input values.
x = Input.GetAxis("Mouse X");
y = Input.GetAxis("Mouse Y");
//Rotate the player right and left
player.transform.Rotate(0, x * speed, 0);
//Look up and down only with your camera
camera.transform.Rotate(y * speed, 0, 0);
}
Answer by JustAbhi · Apr 09, 2020 at 01:06 PM
@azerty0220pl Thanks for the ans. But I am asking how do i make my player move in the direction my camera is facing
Sorry, something like this should work:
public GameObject player;
public float speed;
void Update()
{
if(Input.GetKey(KeyCode.W))
{
player.GetComponent<Rigidbody>().AddForce(player.transform.forward *
speed, Force$$anonymous$$ode.VelocityChange);
}
if(Input.GetKey(KeyCode.A))
{
player.GetComponent<Rigidbody>().AddForce(-player.transform.forward *
speed, Force$$anonymous$$ode.VelocityChange);
}
if(Input.GetKey(KeyCode.D))
{
player.GetComponent<Rigidbody>().AddForce(player.transform.right *
speed, Force$$anonymous$$ode.VelocityChange);
}
if(Input.GetKey(KeyCode.A))
{
player.GetComponent<Rigidbody>().AddForce(-player.transform.right *
speed, Force$$anonymous$$ode.VelocityChange);
}
}
Thanks man Will this work with a mouse rotation too?