I'm pretty new to unity and I decided to make a simple first person game, however my script only allows the player to look around, not move. I have used AddForce, however I am not sure I have done it correctly.
public float walkSpeedForward = 5f;
public float walkSpeedStrafe = 4f;
public float walkSpeedBack = 3f;
public float sprintMultiplier = 2f;
public Camera cam;
public float sensitivityX = 0f;
public float sensitivityY = 0f;
public float minimumX = -360F;
public float maximumX = 360F;
public float minimumY = -60F;
public float maximumY = 60F;
public Rigidbody rb;
float rotationY = 0f;
// Use this for initialization
void Awake () {
rb = GetComponent<Rigidbody>();
rb.freezeRotation = true;
}
// Update is called once per frame
void Update () {
float rotationX = cam.transform.localEulerAngles.y + Input.GetAxis ("Mouse X") * sensitivityX;
rotationY += Input.GetAxis ("Mouse Y") * sensitivityY;
rotationY = Mathf.Clamp (rotationY, minimumY, maximumY);
cam.transform.localEulerAngles = (new Vector3(-rotationY, rotationX, 0f));
}
void FixedUpdate()
{
rb.AddForce (new Vector3 (Input.GetAxis ("Horizontal") * walkSpeedStrafe * Time.deltaTime, 0, Input.GetAxis ("Vertical") * walkSpeedForward * Time.deltaTime));
}
Do not use AddForce, it is physics pushing an object. Not actually Ideal to move a character.
You can learn how to properly make a script or even, use a ready script by clicking
Assets>Import Package> Characters. This package already have characters sounds and the Scripts that you're looking for. You can choose only the scripts if you want, but I suggest for you to import them all since you're trying to learn it. So you would know how to attach sounds, controls, models. As you learn form this package. FYI you don't need to download this, it is already on your computer.
Check this video Click Here
It will only take 12 min of your time.
Related
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CameraSc : MonoBehaviour
{
public float sens;
public Transform body;
public Transform head;
float xRot = 0;
void Start()
{
Cursor.visible = false;
Cursor.lockState = CursorLockMode.Locked;
}
void Update()
{
float x = Input.GetAxisRaw("Mouse X") * sens * Time.deltaTime;
float y = Input.GetAxisRaw("Mouse Y") * sens * Time.deltaTime;
xRot -= y;
xRot = Mathf.Clamp(xRot,-80f,80f);
transform.localRotation = Quaternion.Euler(xRot,0f,0f);
body.Rotate(Vector3.up, x);
transform.position = head.position;
//transform.rotation = head.rotation;
}
}
I have a body and I want my camera to follow my head. it follows of course but it vibrates, its like its not moving , its teleporting to head every second. I tried using FixedUpdate but it was worse. I tried Lerp too but lerp makes camera follow slow, when I move my mouse quick it takes a lot of time to follow.
If you don't need any acceleration or advanced movement for your camera, you can simply make your camera gameobject a child of your head gameobject in the scene hierarchy (or prefab). This will make your camera copy the position and rotation of the head gameobject without any coding.
If you wish to make it third person view, you can simply modify the child position which will always be local to the parent's one.
Hopefully this helps.
It's can be complex problem. Maybe one of these solutions can help.
Why you use Input.GetAxisRaw() - this function return value without smoothing filtering, try Input.GetAxis() as alternative.
"Vibration" effect can be if camera position updates later than your body position. Try setup position for you body object in LateUpdate().
Problem can be in rotation calculation, in your case euler angles will be enough. Try to use something like this:
public float sens = 100.0f;
public float minY = -45.0f;
public float maxY = 45.0f;
private float rotationY = 0.0f;
private float rotationX = 0.0f;
private void Update()
{
rotationX += Input.GetAxis("Mouse X") * sens * Time.deltaTime;
rotationY += Input.GetAxis("Mouse Y") * sens * Time.deltaTime;
rotationY = Mathf.Clamp(rotationY, minY, maxY);
transform.localEulerAngles = new Vector3(-rotationY, rotationX, 0);
}
I made this script for my Player object. It has to child, 1 camera and 1 model.
They problem is whenever i move my mouse the player moves down. and the cam goes up.
Script:
public GameObject cam;
public float sensitivity = 2f;
public float walk_speed = 2f;
public float run_speed = 2f;
CharacterController player_CC;
float speed;
float moveFB;
float moveLR;
float rotX;
float rotY;
bool canMove;
void Start () {
canMove = true;
player_CC = GetComponent<CharacterController>();
speed = walk_speed;
}
void Update () {
if (canMove)
{
moveFB = Input.GetAxis("Vertical") * speed;
moveLR = Input.GetAxis("Horizontal") * speed;
rotX = Input.GetAxis("Mouse X") * sensitivity;
rotY = Input.GetAxis("Mouse Y") * sensitivity;
Vector3 movement = new Vector3(moveLR, 0, moveFB);
transform.Rotate(0, rotX, 0);
cam.transform.Rotate(rotY, 0, 0);
movement = transform.rotation * movement;
player_CC.Move(movement * Time.deltaTime);
}
if (Input.GetKey(KeyCode.LeftShift))
{
speed = run_speed;
} else
{
speed = walk_speed;
}
}
movement = transform.rotation * movement;
You're multiplying your transforms rotation by your movement vector. Separate the logic.
I know what caused it. But i dont know why it did it. But i used a charachtercontroller and a rigidbody on the same object. Sorry for wasting your time :/
I'm making a game in Unity 5 (3D) and am using c# for scripting. So I basically have a third person dude running around with 8 direction controls (WASD) and the way I have set it up now is like this (ignore all the public variables for testing):
public class Player8D : MonoBehaviour
{
public float moveSpeed;
public float moveSpeedMax = 13.5F;
public float turnSpeed = 4F;
public float transitionSpeed = 10F;
private float moveSmooth = 0.0F;
public float moveSmoothTime = 10F;
private Animator anim;
private Rigidbody rb;
private CharacterController cc;
void Start()
{
anim = gameObject.GetComponentInChildren<Animator>();
rb = gameObject.GetComponentInChildren<Rigidbody>();
cc = gameObject.GetComponentInChildren<CharacterController>();
}
void Update()
{
Vector3 NextDir = new Vector3(Input.GetAxisRaw("Horizontal"), 0, Input.GetAxisRaw("Vertical"));
if (NextDir != Vector3.zero) //When movement input is happening
{
anim.SetInteger("Run", 1); //Animation stuff
transform.rotation = Quaternion.Slerp(transform.rotation, Quaternion.LookRotation(NextDir), Time.deltaTime * turnSpeed);
moveSpeed = Mathf.SmoothDamp(moveSpeed, moveSpeedMax, ref moveSmooth, moveSmoothTime / 100);
} else
{
moveSpeed = Mathf.SmoothDamp(moveSpeed, 0.00F, ref moveSmooth, transitionSpeed / 100);
anim.SetInteger("Run", 0); //Animation stuff
anim.CrossFade("Idle", transitionSpeed / 100);
}
transform.Translate(Vector3.forward * Time.deltaTime * moveSpeed); //Movement code
}
}
This gave me the best feeling due to how it moves in the direction it's facing, rather than in 8 distinct world directions like with cc.Move. That being said it has the caveat of not being in physics, which I kinda need for OnTriggerEnter and falling realistically and it makes going uphill strange. I have no idea how to manage the rb.AddForce or AddRelativeForce functions, as they don't move my character when I replace transform.Translate with them, no matter how great the force is.
How do I change the code and components to get my character moving through physics?
Here is a screenshot of my scene hierarchy:
So I'm trying to make an FPS-type game and is it possible to have a GameObject locked on the Y-axis/not able to move up or down? The GameObject is a model of an AWP from Counter Strike, I am making it move around the plane with the WASD keys, and when I use the mouse to look up/down, the AWP goes diagonally to where I'm looking, and I don't want that. My game looks like this: Screenshot
Here's the code I have for the AWP if it helps:
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class AWPscript : MonoBehaviour {
public float speed = 5f;
// public float sensitivityX = 15.0f;
// public float sensitivityY = 15.0f;
public Camera MainCamera;
public Camera scopeCamera;
public float lookSensitivity = 10f;
public float xRotation ;
public float yRotation ;
public float currentXRotation;
public float currentYRotation;
public float xRotationV;
public float yRotationV;
public GameObject Scopepng;
public float lookSmoothDamp = 0.1f;
public Image ScopePNG;
public AudioClip sound;
// Use this for initialization
void Start () {
speed = 7.5f;
}
// Update is called once per frame
void Update () {
if(Input.GetKey(KeyCode.W))
transform.Translate(Vector3.forward * Time.deltaTime*speed);
if (Input.GetKey(KeyCode.S))
transform.Translate(Vector3.back * Time.deltaTime * speed);
if (Input.GetKey(KeyCode.A))
transform.Translate(Vector3.left * Time.deltaTime * speed);
if (Input.GetKey(KeyCode.D))
transform.Translate(Vector3.right * Time.deltaTime * speed);
if (Input.GetKey(KeyCode.LeftControl))
speed = 15f;
lookAround();
scope();
}
void scope()
{
if (Input.GetMouseButton(1))
{
MainCamera.enabled = false;
scopeCamera.enabled = true;
ScopePNG.enabled = true;
}
else
{
MainCamera.enabled = true;
scopeCamera.enabled = false;
ScopePNG.enabled = false;
}
}
void lookAround()
{
xRotation -= Input.GetAxis("Mouse Y") * lookSensitivity;
yRotation += Input.GetAxis("Mouse X") * lookSensitivity;
transform.rotation = Quaternion.Euler(xRotation, yRotation, 0);
}
}
Here's probably the simplest solution:
void Update () {
if(Input.GetKey(KeyCode.W))
transform.Translate(Vector3.forward * Time.deltaTime*speed);
if (Input.GetKey(KeyCode.S))
transform.Translate(Vector3.back * Time.deltaTime * speed);
if (Input.GetKey(KeyCode.A))
transform.Translate(Vector3.left * Time.deltaTime * speed);
if (Input.GetKey(KeyCode.D))
transform.Translate(Vector3.right * Time.deltaTime * speed);
if (Input.GetKey(KeyCode.LeftControl))
speed = 15f;
LookAround();
Scope();
JoeFix();
}
public float fixedFloatingHeightMeters; // set to say 1.4 in the editor
private void JoeFix()
{
Vector3 p = transform.position;
p.y = fixedFloatingHeightMeters;
transform.position = p;
}
PS! you really MUST rename lookAround to LookAround and scope to Scope. It can affect things later
Here's kind of an advanced piece of information that may be more what you want. Please try this also!
Currently you have a vector that is the NOSE OF THE OBJECT pointing.
Say the thing is heading NORTH, ok?
So, transform.forward is pointing North BUT, IT IS POINTING "DOWN A BIT".
Although it is pointing north, if you saw it from the side that vector is pointing DOWN A BIT.
What you really want is that vector, but FLAT, NOT POINTING DOWN OR UP. Right?!
In fact here's the magic to do that:
Vector3 correctDirectionButPossiblyDownOrUp = transform.forward;
Vector3 correctDirectionButFlatNoDownOrUp;
correctDirectionButFlatNoDownOrUp
= Vector3.ProjectOnPlane(
correctDirectionButPossiblyDownOrUp,
Vector3.up );
correctDirectionButFlatNoDownOrUp.Normalize();
correctDirectionButFlatNoDownOrUp is now the "magic" vector you want.
But, don't forget Translate works in LOCAL SPACE. (the "object's" idea of the world.) You very much want to move it in world space, which is easy. Notice the last argument: https://docs.unity3d.com/ScriptReference/Transform.Translate.html
transform.Translate(
correctDirectionButFlatNoDownOrUp * Time.deltaTime*speed,
Space.World);
So that's it !
footnote Don't forget "Vector3.up" has absolutely no connection to "Vector3".
If you don't need the gravity then removing the RigidBody component will stop Unity applying gravity and it will hover.
Very new to mono develop and Unity 3d and seem to be having issues with this code. First off, the code IS working. It does what it's supposed to, however, it also does some funky stuff that it's not supposed to. You are able to look up, down, left and right as well as walk those directions, the bad part is though for some reason my character likes to nudge the direction of the mouse when standing still. What am I missing? More efficient/less buggy way of doing this?
public class PlayerControl : MonoBehaviour {
public float WALK_SPEED = 1.3f;
public float RUN_SPEED = 4.0f;
public float STRAFE_SPEED = 5.0f;
public float ROTATION_SPEED = 300.0f;
public float JUMP_FORCE = 250.0f;
void Start()
{
}
// Update is called once per frame
void Update ()
{
float movementSpeed = WALK_SPEED;
float strafeSpeed = STRAFE_SPEED;
float rotationSpeedx = ROTATION_SPEED;
float rotationSpeedy = ROTATION_SPEED;
if (Input.GetKey(KeyCode.LeftShift))
{
movementSpeed = RUN_SPEED;
}
movementSpeed = Input.GetAxis("Vertical") * movementSpeed * Time.deltaTime;
strafeSpeed = Input.GetAxis("Horizontal") * strafeSpeed * Time.deltaTime;
rotationSpeedx = Input.GetAxis("Mouse X") * rotationSpeedx * Time.deltaTime;
rotationSpeedy = Input.GetAxis("Mouse Y") * rotationSpeedy * Time.deltaTime;
Vector3 rotate = new Vector3 (-rotationSpeedy, rotationSpeedx, 0);
transform.Translate(Vector3.forward * movementSpeed);
transform.Translate(Vector3.right * strafeSpeed);
transform.Rotate(rotate);
if (Input.GetKeyDown(KeyCode.Space) &&
transform.position.y < 30)
{
rigidbody.AddForce(Vector3.up * JUMP_FORCE);
}
}
}
Try freezing rotation constraints on rigidbody component. This may stop the nudging.