Hey i started unity and scripting yesterday and found some way to make my character move but i feel like the movement is not smooth and i can say a bit buggy
Here is my codes :
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Test : MonoBehaviour
{
public float Speed;
void Update()
{
Move();
}
private void Move()
{
if (Input.GetKey(KeyCode.W)) { transform.Translate(Vector3.forward * Time.deltaTime * Speed); }
if (Input.GetKey(KeyCode.S)) { transform.Translate(-1 * Vector3.forward * Time.deltaTime * Speed); }
if (Input.GetKey(KeyCode.D)) { transform.Translate(Vector3.right * Time.deltaTime * Speed); }
if (Input.GetKey(KeyCode.A)) { transform.Translate(-1 * Vector3.right * Time.deltaTime * Speed); }
}
}
This is the code that lets me move my character and i have another code to rotate my character :
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class RotatePlayer : MonoBehaviour
{
public float MouseSpeed;
public Camera Camera;
void Start()
{
// Locks Cursor in the middle of the screen
Cursor.lockState = CursorLockMode.Locked;
}
void Update()
{
//Rotate Only X Collider
transform.eulerAngles += MouseSpeed * new Vector3(0, Input.GetAxis("Mouse X"), 0);
//Rotate Y Camera
Camera.transform.eulerAngles += MouseSpeed * new Vector3(-Input.GetAxis("Mouse Y"), 0, 0);
}
}
I don’t see anything in your scripts that would cause your character to not move smoothly. But it’s possible that you’re referring to the instant acceleration that’s happening. You can prevent this by using Input.GetAxis which returns a smoothed value in the range of -1 to 1 and so the acceleration will be gentler.
So like this:
using UnityEngine;
public class Test : MonoBehaviour
{
public float Speed;
void Update()
{
Move();
}
void Move()
{
transform.Translate(new Vector3(Input.GetAxis("Horizontal"),0,Input.GetAxis("Vertical")) * Time.deltaTime * Speed);
}
}
Although in general the above is not how you would move a character around because it’s movement won’t be deflected when colliding with walls. Instead you should add a rigidbody to your character and move it around with methods like AddForce.
using UnityEngine;
public class Test : MonoBehaviour
{
public float speed;
Rigidbody rb;
void Start()
{
rb=GetComponent<Rigidbody>();
rb.freezeRotation=true;
}
void FixedUpdate()
{
Vector3 input=new Vector3(Input.GetAxisRaw("Horizontal"),0,Input.GetAxisRaw("Vertical")).normalized;
rb.AddRelativeForce(input * speed);
}
}
Thank you for answering but the second code doesnt work, i don’t know why because i’m no expert but it doesnt work and also how can i make my character jump ?
Edit - It works i just have to put a really high speed