Rigidbody GameObject is restricted in movement while moving - c#

So I'm pretty new to Unity, but I managed to put together a script that moves the player around a plane. Problem is, after moving a certain distance, it won't move any further. I want the movement to be unrestricted.
using UnityEngine;
public class Movement_Player : MonoBehaviour
{
public Rigidbody rb;
public float default_speed;
public float sprint_multiplier;
private float speed;
private void Update()
{
speed = default_speed;
float horizontal = Input.GetAxis("Horizontal");
float vertical = Input.GetAxis("Vertical");
Vector3 movement = new Vector3(horizontal, 0.0f, vertical);
if (Input.GetKey(KeyCode.LeftShift))
speed = speed * sprint_multiplier;
else
speed = default_speed;
rb.MovePosition(movement * speed);
}
}

You need to move your MovePosition outside of Update to FixedUpdated.
FixedUpdate is the right place to put physic code.
You need too to reset your movement vector on each update if you like to get the new displacement vector to skip a drag movement and need to add timefactor * Time.fixedDeltaTime
using UnityEngine;
public class Movement_Player : MonoBehaviour
{
public Rigidbody rb;
public float default_speed;
public float sprint_multiplier;
private float speed;
private void Update()
{
Vector3 movement = Vector3.zero
speed = default_speed;
float horizontal = Input.GetAxis("Horizontal");
float vertical = Input.GetAxis("Vertical");
Vector3 movement = new Vector3(horizontal, 0.0f, vertical);
if (Input.GetKey(KeyCode.LeftShift))
speed = speed * sprint_multiplier;
else
speed = default_speed;
}
void FixedUpdate()
{
rb.MovePosition(rb.position + movement * speed * Time.fixedDeltaTime);
}
}

Related

How to make the player walk in the direction it is pointing?

I made a simple movement system in Unity 3D, but I don't know how to make it so that I move in the direction my player is pointing in.
using UnityEngine;
public class PlayerControler : MonoBehaviour
{
CharacterController characterController;
public float MovementSpeed = 1f;
public float Gravity = 9.8f;
private float velocity = 0f;
void Start()
{
characterController = GetComponent<CharacterController>();
}
void Update()
{
float horizontal = Input.GetAxis("Horizontal") * MovementSpeed;
float vertical = Input.GetAxis("Vertical") * MovementSpeed;
characterController.Move((Vector3.right * horizontal + Vector3.forward * vertical) * Time.deltaTime);
if (characterController.isGrounded)
{
velocity = 0;
}
else
{
velocity -= Gravity * Time.deltaTime;
characterController.Move(new Vector3(0, velocity, 0));
}
}
}
This is the player controller.
using UnityEngine;
public class MouseControl : MonoBehaviour
{
public float horizontalSpeed = 1f;
public float verticalSpeed = 1f;
private float xRotation = 0.0f;
private float yRotation = 0.0f;
private Camera cam;
void Start()
{
cam = Camera.main;
}
void Update()
{
float mouseX = Input.GetAxis("Mouse X") * horizontalSpeed;
float mouseY = Input.GetAxis("Mouse Y") * verticalSpeed;
yRotation += mouseX;
xRotation -= mouseY;
xRotation = Mathf.Clamp(xRotation, -90f, 90f);
cam.transform.eulerAngles = new Vector3(xRotation, yRotation, 0.0f);
}
}
This is the code that makes my character face where my cursor is.
Edit: This is a First-Person 3D game. The player has a CharacterControler component on it, and the Main Camera is a child of the player. The second piece of code changes the direction that the camera is facing when the cursor is moved. The first script is the movement script, and utilises the CharacterController component of the player to move. I want to make to that instead of going in four static directions every time I press a movement key, I want the player to move in proportion to the direction that the camera is facing (on the X axis). E.g: If I am facing West and I press “W” to go forwards, I want the character to go West instead of North.
Instead of the global vectors Vector3.forward and Vector3.right in
characterController.Move((Vector3.right * horizontal + Vector3.forward * vertical) * Time.deltaTime);
rather use your local direction vectors Transform.forward and Transform.right
characterController.Move((transform.right * horizontal + transform.forward * vertical) * Time.deltaTime);
#derHugo was right, but I forgot to update the angles in the player movement script, so it always thought that I was rotated 0,0,0.
using UnityEngine;
public class PlayerControler : MonoBehaviour
{
Vector3 angles;
CharacterController characterController;
MouseControl mouseControl;
public float MovementSpeed = 1f;
public float Gravity = 9.8f;
private float velocity = 0f;
void Start()
{
characterController = GetComponent<CharacterController>();
mouseControl = GetComponent<MouseControl>();
}
void Update()
{
angles = new Vector3(mouseControl.xRotation, mouseControl.yRotation, 0f);
transform.eulerAngles = angles;
float horizontal = Input.GetAxis("Horizontal") * MovementSpeed;
float vertical = Input.GetAxis("Vertical") * MovementSpeed;
characterController.Move((transform.right * horizontal + transform.forward * vertical) * Time.deltaTime);
if (characterController.isGrounded)
{
velocity = 0;
}
else
{
velocity -= Gravity * Time.deltaTime;
characterController.Move(new Vector3(0, velocity, 0));
}
}
}
Updated code
Note: I had to made the X and Y rotation variables public.
[HideInInspector]public float xRotation = 0.0f;
[HideInInspector]public float yRotation = 0.0f;

Player gravity turns off while i move in Unity

I am quite new to unity and I have two scripts, one for gravity and one for player movement as the names suggest. The reason I am using a gravity script is that the third person movement doesn't support using a rigidbody with position and rotation enabled, so I have frozen the position and the rotation inside the rigidbody (which turns off gravity in the rigidbody). I made the Gravity script myself but I followed a tutorial on the player movement script because I have no idea how to make third person movement so I don't really know what is going on in the movement script.
Movement script:
public class ThirdPersonMovement : MonoBehaviour
{
public CharacterController controller;
public Transform cam;
public float speed = 6f;
public float turnSmoothTime = 0.1f;
float turnSmoothVelocity;
void Update()
{
float horizontal = Input.GetAxisRaw("Horizontal");
float vertical = Input.GetAxisRaw("Vertical");
UnityEngine.Vector3 direction = new UnityEngine.Vector3(horizontal, 0f, vertical).normalized;
if (direction.magnitude >= 0.1f)
{
float targetAngle = Mathf.Atan2(direction.x, direction.z) * Mathf.Rad2Deg + cam.eulerAngles.y;
float angle = Mathf.SmoothDampAngle(transform.eulerAngles.y, targetAngle, ref turnSmoothVelocity, turnSmoothTime);
transform.rotation = UnityEngine.Quaternion.Euler(0f, angle, 0f);
UnityEngine.Vector3 moveDir = UnityEngine.Quaternion.Euler(0f, targetAngle, 0f) * UnityEngine.Vector3.forward;
controller.Move(moveDir.normalized * speed * Time.deltaTime);
}
}
}
Gravity script:
public class gravityScript : MonoBehaviour
{
public float GravitySpeed = -0.03f;
public bool GravityCheck = false;
void OnCollisionEnter(Collision col)
{
if (col.gameObject.name == "Terrain0_0")
{
GravityCheck = true;
}
}
void OnCollisionExit(Collision col)
{
GravityCheck = false;
}
void Update()
{
if (GravityCheck == false)
{
transform.Translate(0, GravitySpeed, 0);
}
}
}
Thank you in advance :)
I don't know what happened but when I opened it today (the day after posting) it was working fine. It was likely just a bug that got fixed after a restart.

Have enemy accelerate towards player in Unity

I have a script that has the enemy move towards the player at the same speed, but I am trying to make the enemy slow down then accelerate when he is switching directions. The enemy currently just moves left and write towards the player's position.
Here is my code from the script that my boss is attached to in the update function:
Vector2 targetPosition = new Vector2 (player.transform.position.x, transform.position.y);
transform.position = Vector2.MoveTowards (transform.position, targetPosition, moveSpeed * Time.deltaTime);
I have also tried using Lerp and using the transform.position as the first parameter, but the boss goes slower when the player is closer, and faster when the player is faster away.
transform.position = Vector2.Lerp (transform.position, targetPosition, moveSpeed * Time.deltaTime);
Does anyone know how to make the enemy slow down, then gradually increase his speed as he change direction, then return to normal speed after he has finished changing directions
**EDIT: ** full script below
using UnityEngine;
public class Roll : StateMachineBehaviour
{
[SerializeField] private float moveSpeed = 2.4f;
[SerializeField] private float rotateSpeed = 100f;
[SerializeField] private float minRollTime = 6f;
[SerializeField] private float maxRollTime = 8f;
private float rollTimer = 0f;
[SerializeField] private float rightBoundary = 5f;
[SerializeField] private float leftBoundary = -5f;
private Transform playerTransform = null;
private BossHealth bossHealth = null;
private Transform bossTransform = null;
private Transform bodyTransform = null;
private Transform earsTransform = null;
private Vector2 targetPosition = Vector2.zero;
override public void OnStateEnter(Animator animator, AnimatorStateInfo stateInfo, int layerIndex)
{
playerTransform = GameObject.FindWithTag("Player").transform;
bossHealth = animator.GetComponent<BossHealth>();
Boss01 boss = FindObjectOfType<Boss01>();
bossTransform = boss.bossTransform;
bodyTransform = boss.bodyTransform;
earsTransform = boss.earsTransform;
rollTimer = Random.Range (minRollTime, maxRollTime);
}
override public void OnStateUpdate(Animator animator, AnimatorStateInfo stateInfo, int layerIndex)
{
if (bossTransform.position.x >= leftBoundary && bossTransform.position.x <= rightBoundary)
{
targetPosition = new Vector2(playerTransform.position.x, bossTransform.position.y);
bossTransform.position = Vector2.MoveTowards(bossTransform.position, targetPosition, moveSpeed * Time.deltaTime);
if (playerTransform.position.x > 0)
bodyTransform.Rotate(0f, 0f, -rotateSpeed * Time.deltaTime);
else
bodyTransform.Rotate(0f, 0f, rotateSpeed * Time.deltaTime);
}
else if (bossTransform.position.x < leftBoundary)
{
if (playerTransform.position.x > bossTransform.position.x)
{
targetPosition = new Vector2(playerTransform.position.x, bossTransform.position.y);
bossTransform.position = Vector2.MoveTowards(bossTransform.position, targetPosition, moveSpeed * Time.deltaTime);
}
}
else
{
if (playerTransform.position.x < bossTransform.position.x)
{
targetPosition = new Vector2(playerTransform.position.x, bossTransform.position.y);
bossTransform.position = Vector2.MoveTowards(bossTransform.position, targetPosition, moveSpeed * Time.deltaTime);
}
}
if (rollTimer <= 0f)
animator.SetTrigger ("aim");
else
rollTimer -= Time.deltaTime;
if (bossHealth.CheckHealth())
animator.SetTrigger ("transition");
if (earsTransform.rotation != Quaternion.Euler (0f, 0f, 0f))
earsTransform.rotation = Quaternion.Slerp(earsTransform.rotation, Quaternion.Euler(0f, 0f, 0f), 1f * Time.deltaTime);
}
override public void OnStateExit(Animator animator, AnimatorStateInfo stateInfo, int layerIndex)
{
animator.ResetTrigger ("aim");
animator.ResetTrigger ("transition");
}
}
To achieve the position (meters/second) you multiply the speed * Time.deltatime, so you achieve the meters. To handle acceleration, you need to handle variable speed. Acceleration is m/s2, multiplied * Time.deltatime you will have the instant speed, and that speed * Time.deltaTime will give you the position.
Here some pseudocode (step and speed should be class varibles and this modifieed in the update. accel is the constant acceleration, that should be constans for the simplicity's sake, I guess that you need uniformingly accelerated movement):
speed += accel * Time.deltaTime; // instant speed
step = speed * Time.deltaTime; // calculate distance to move
transform.position = Vector3.MoveTowards(transform.position, target.position, step);
With the sign of the accel + or - you will determine if the entities speed is increasing (accelerating) or decreasing (decelerating).
Hope that helps
Edit:
Full script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MoveTowards : MonoBehaviour
{
public Transform target;
private float step = 0f;
private float speed = 0f;
public float accel = 0f;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
speed += accel * Time.deltaTime; // instant speed
step = speed * Time.deltaTime; // calculate distance to move
transform.position = Vector3.MoveTowards(transform.position, target.position, step);
}
}
Screenshot of script attached in editor:
Attached the script to the game object you want to move, and attach the transform of the target in the public fielld. The choose your acceleration, positive to accelerate towards an negative to accelerate backwars, and there you got it.

Can't rotate and move at the same time

I'm currently developing an FPS shooter in Unity 3D. I'm fairly new to Unity and I've been having a bit of trouble with my player movement script. Individually everything seems to work, I can rotate and move the player freely, however when I try doing the two simultaneously my player seems to lock and won't rotate.
Sometimes jumping or moving to higher ground on the terrain seems to fix the issue, however I ran a few checks with gravity disabled, no colliders, and with the player well above ground, so the problem seems to be with the script. I've also done a bit of debugging and the Rotate() code does run, just the rotation amount doesn't seem to change.
Here is the player movement script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[RequireComponent(typeof(Rigidbody))]
public class PlayerMov : MonoBehaviour
{
[SerializeField]
private Camera cam;
[SerializeField]
private float speed = 5f;
[SerializeField]
private float looksensitivity = 4f;
[Header("Camera View Lock:")]
[SerializeField] //min and max amount for looking up and down (degrees)
private float lowlock = 70f;
[SerializeField]
private float highlock = 85f;
private Rigidbody rb;
private float currentrotx; //used later for calculating relative rotation
public Vector3 velocity;
public Vector3 rotation; // rotates the player from side to side
public float camrotation; // rotates the camera up and down
public float jmpspe = 2000f;
void Start()
{
rb = GetComponent<Rigidbody>();
}
// Update is called once per frame
void Update()
{
CalcMovement();
CalcRotation();
Rotate();
}
void FixedUpdate()
{
Move();
}
private void CalcRotation()
{
float yrot = Input.GetAxisRaw("Mouse X"); //around x axis
rotation = new Vector3(0f, yrot, 0f) * looksensitivity;
float xrot = Input.GetAxisRaw("Mouse Y"); //around y axis
camrotation = xrot * looksensitivity;
}
private void CalcMovement()
{
float xmov = Input.GetAxisRaw("Horizontal");
float zmov = Input.GetAxisRaw("Vertical");
Vector3 movhor = transform.right * xmov;
Vector3 movver = transform.forward * zmov;
velocity = (movhor + movver).normalized * speed;
}
void Move()
{
//move
if (velocity != Vector3.zero)
{
rb.MovePosition(rb.position + velocity * Time.fixedDeltaTime);
}
//jump
if (Input.GetKeyDown(KeyCode.Space))
{
//add double jump limit later!
rb.AddForce(0, jmpspe * Time.deltaTime, 0, ForceMode.Impulse);
}
}
void Rotate()
{
//looking side to side
rb.MoveRotation(rb.rotation * Quaternion.Euler(rotation));
// camera looking up and down
currentrotx -= camrotation;
currentrotx = Mathf.Clamp(currentrotx, -lowlock, highlock);
cam.transform.localEulerAngles = new Vector3(currentrotx, 0, 0);
}
}
Here are the relevant components attached to my player:
(The player has a couple more components attached but I ran tests without them and the problem still occurs)
Like I said I'm a bit of a unity novice, so i'm sure I missed something small but I just can't seem to place my finger on it, I've been stuck on this for a while so any help is much appreciated.
SOLVED:
It seems the problem I had was because I was running the scene from my laptop and not a desktop which I assume is what the Unity input was built for.

Unity Rotate ball left or right insted of roll

I'm trying to learn Unity3D and I'm using this tutorial to get started.
In my PlayerController below the "ball" rolls in the direction of the arrow key pressing. But my question is: When I press left or right arrow I don't want it to move in the direction but to turn in the direction.
So the ball moves forward/backward on arrow key up/down and rotate left/right on arrow key left/right.
public class PlayerController : MonoBehaviour {
public float speed;
private Rigidbody rb;
void Start()
{
rb = GetComponent<Rigidbody> ();
}
void FixedUpdate()
{
float moveHorizontal = Input.GetAxis("Horizontal");
float moveVertical = Input.GetAxis("Vertical");
Vector3 movement = new Vector3 (moveHorizontal, 0.0f, moveVertical);
rb.AddForce (movement * speed);
}
}
I've searched on google but haven't been able to find a solution.
UPDATE
Here is my camera controller.
public class CameraController : MonoBehaviour {
public GameObject player;
private Vector3 offset;
// Use this for initialization
void Start () {
offset = transform.position - player.transform.position;
}
// Update is called once per frame
void LateUpdate () {
transform.position = player.transform.position + offset;
}
}
float delta = Input.GetAxis("Horizontal");
Vector3 axis = Vector3.forward;
rb.AddTorque (axis * speed * delta);
or
transform.Rotate (axis * speed * delta);
Instead of:
rb.AddForce (movement * speed);
you can use:
rb.AddTorque (movement * speed);
This will add angular force to the ball.

Categories