Unity rotate while moving forward - c#

I have the following code for my 2D game, it makes object randomly wonder on the screen. What I am having issues with, is when an object looks at the point it is going to, I would like it to rotate as it moves forward. What is happening now, is it rotates instantly to the point it is going towards. So, how can I get it to rotate slowly and move forward at the same time?
using UnityEngine;
using System.Collections;
public class Wonder : MonoBehaviour {
protected Vector2 wayPoint;
protected float speed;
// Use this for initialization
void Start () {
speed = gameObject.GetComponent<Move>().playerSpeed;
wonder();
}
void wonder(){
wayPoint = Random.insideUnitCircle * 10;
}
// Update is called once per frame
void Update () {
Vector2 dir = wayPoint - new Vector2(transform.position.x, transform.position.y);
float angle = Mathf.Atan2(dir.y, dir.x) * Mathf.Rad2Deg;
transform.rotation = Quaternion.Euler(new Vector3(0, 0,Mathf.Atan2 (dir.y, dir.x) * Mathf.Rad2Deg - 90));
transform.position = Vector2.MoveTowards(transform.position, wayPoint, Time.deltaTime * speed);
float magnitude = (new Vector2(transform.position.x, transform.position.y) - wayPoint).magnitude;
if(magnitude < 3){
wonder();
}
}
}
Here is an example Image:
So, once the ship gets to its point another will be created and it will move there. I am thinking I will have to have a list of 5+ points, then calculate the arch the ship needs to take adding new points as the ship hits a way point then removing old ones after. I am not sure how to do this though...

using UnityEngine;
using System.Collections;
public class Wander : MonoBehaviour {
protected Vector3 velocity;
protected Vector2 waypoint;
protected float speed;
// Use this for initialization
void Start () {
speed = gameObject.GetComponent<Move>().playerSpeed;
RandomizeWaypoint();
}
void RandomizeWaypoint(){
waypoint = Random.insideUnitCircle * 10;
}
// Update is called once per frame
void Update () {
transform.position = Vector3.SmoothDamp( transform.position, waypoint, ref velocity, Time.deltaTime * speed );
transform.rotation = Quaternion.AngleAxis( Mathf.Atan2( velocity.y, velocity.x ) * Mathf.Rad2Deg, Vector3.forward );
if( Vector3.Distance( transform.position, waypoint ) < 3 ){
RandomizeWaypoint();
}
}
}
Untested. Vector3.SmoothDamp can be pretty handy. Note the spelling also.

Related

how do i Rotate and move 3rd person character at Unity

I want to rotate my player for where my mouse is pointing and move the player with "WASD" keys.
I'm actually succesfully rotating my player and moving it, but it doesn't move right depending where my mouse is pointing.. the player just move everytime to the same position.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerController : MonoBehaviour
{
public int playerSpeed = 5;
public float sensitivity = 5.0f;
public bool blockMouse = true;
private float mouseX;
void Start(){
BlockMouse();
}
void Update() {
Move();
Rotate();
}
void Move()
{
Vector3 movement = new Vector3 (Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));
transform.position += movement * playerSpeed * Time.deltaTime;
if(Input.GetKeyDown(KeyCode.LeftShift)) {
playerSpeed=10;
} else if(Input.GetKeyUp(KeyCode.LeftShift)) {
playerSpeed=5;
}
}
void Rotate() {
mouseX += Input.GetAxis("Mouse X") * sensitivity;
transform.eulerAngles = new Vector3(0, mouseX, 0);
}
void BlockMouse() {
if (!blockMouse) {
return;
}
Cursor.visible = false;
Cursor.lockState = CursorLockMode.Locked;
}
}
``
Assuming the rotation is working as you said
transform.position += movement * playerSpeed * Time.deltaTime;
by doing this you change the objects world space absolute position, not taking any rotation into account.
Now there are probably a lot of ways how do rather do this
You could simply take the rotation into account
transform.position += transform.rotation * movement * playerSpeed * Time.deltaTime;
This simply stays in world space but rotates your world space vector accordingly
You could rather use Translate
transform.Translate(movement * playerSpeed * Time.deltaTime);
which basically does the same, takes orientation into account but is not affected by scaling

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 bouncing when colliding with object

I have made a script with movement, that finally works as i want it to, except one thing... I want it to be a first person game, but the way the movement works now, is on the global axis, which means that W is always torwards one specific direction, no matter what direction my camera is turning... How do i fix this? i want the movement to stay how it is, but with the W key to always be forward depending on the way the camera or player is looking.
Please let me know how my script would look edited, or atleast what part i have to change.
I would also like to add that i would love to be able to do a wall jump, but i am not sure how to add that behavior.
Here is my movement script:
public class MovementScript : MonoBehaviour {
public float speed;
public float jumpforce;
public float gravity = 25;
private Vector3 moveVector;
private Vector3 lastMove;
private float verticalVelocity;
private CharacterController controller;
// Use this for initialization
void Start () {
controller = GetComponent<CharacterController> ();
//Låser og gemmer musen
Cursor.lockState = CursorLockMode.Locked;
}
// Update is called once per frame
void Update () {
//Låser musen op
if (Input.GetKeyDown ("escape"))
Cursor.lockState = CursorLockMode.None;
moveVector = Vector3.zero;
moveVector.x = Input.GetAxis("Horizontal");
moveVector.z = Input.GetAxis("Vertical");
if (controller.isGrounded) {
verticalVelocity = -1;
if (Input.GetButton("Jump")) {
verticalVelocity = jumpforce;
}
} else {
verticalVelocity -= gravity * Time.deltaTime;
moveVector = lastMove;
}
moveVector.y = 0;
moveVector.Normalize ();
moveVector *= speed;
moveVector.y = verticalVelocity;
controller.Move (moveVector * Time.deltaTime);
lastMove = moveVector;
}
}
You need to go from local to world space:
for example when you want to move on the x-axis regarding the player's orientation, the local vector is (1, 0, 0), which you get from your input axis, but the CharacterController need a world based direction (see the doc of the Move function)
A more complex move function taking absolute movement deltas.
To get this, use Transform.TransformDirection like this
worldMove = transform.TransformDirection(moveVector);
controller.Move (worldMove * Time.deltaTime);
EDIT regarding your issue with the controller moving a bit after releasing the input:
That's because GetAxis gives you a smoothed value. Replace GetAxis by GetAxisRaw and it should work
Modify the final moving code to
controller.Move(moveVector.z * transform.forward * Time.deltaTime);
controller.Move(moveVector.x * transform.right * Time.deltaTime);
controller.Move(moveVector.y * transform.up * Time.deltaTime);
Alternatively, suppose your character is only rotated about the Y axis, you can look into rotating your moveVector by your character's Y rotation so moveVector's forward points parallel to your chracter's forward.
I found a good explaination of rotating a vector here: https://answers.unity.com/questions/46770/rotate-a-vector3-direction.html
Rotating a vector:
moveVector = Quaternion.Euler(0, transform.eulerAngles.y, 0) * moveVector;

Changing player direction with keys using C# in Unity

Ive been trying to make this Object move forward on its own and turn left or right in circular fashion if the left/right keys are pressed with unity using C#, this picture will make it clearer: http://prnt.sc/avmxbn
I was only able to make it move on its own and this is my code so far:
using UnityEngine;
using System.Collections;
public class PlayerBehaviour : MonoBehaviour {
Update(){ transform.localPosition += transform.forward *speed *Time.deltaTime
float speed = 5.0f;
// Use this for initialization
void Start () {
Debug.Log ("it's working?");
}
// Update is called once per frame
void Update () {
transform.localPosition += transform.forward * speed * Time.deltaTime;
}
void FixedUpdate(){
}
}
I have no idea, however, how to change left or right directions in circular paths like the picture linked demonstrates. Anyone able to help me? Thank you.
There are obvious errors in your code. You call Update() twice. The first time without a return type. You shouldn't do that. Start by deleting the first Update() and the code on the same line.
Then to answer your question you will have to look into getting input from the user. Use Input.GetKey() and pass it a KeyCode value such as KeyCode.Afor the 'A' key. So you can say:
if(Input.GetKey(KeyCode.A))
{
//do something(for example, Turn the player right.)
}
Then look into rotating the object using transform.Roate to rotate the player.
Attach this script to your moving object:
using UnityEngine;
public class MoveController : MonoBehaviour {
float angle = 1F;
float speed = 0.2F;
void Update ()
{
if ( Input.GetKey (KeyCode.LeftArrow) )
transform.Rotate(Vector3.up, -angle);
else if( Input.GetKey (KeyCode.RightArrow) )
transform.Rotate(Vector3.up, angle);
transform.Translate(Vector3.forward * speed);
}
}
The key point here is to separate your moving from your rotating functionality.
You can use this script for movement :
using UnityEngine;
public class MovementController : MonoBehaviour {
public Rigidbody rigidbody;
float angle = 0f;
const float SPEED = 1f;
float multiplier = 1f;
void FixedUpdate(){
if ( Input.GetKey (KeyCode.LeftArrow) )
angle -= Time.deltaTime * SPEED * multiplier;
else if( Input.GetKey (KeyCode.RightArrow) )
angle += Time.deltaTime * SPEED * multiplier;
rigidbody.velocity = new Vector2(Mathf.Sin(angle) * SPEED, Mathf.Cos(angle) * SPEED);
}
}
Multiplier value is inversely proportional to the radius.

changing object direction with keys in C#, Unity [duplicate]

Ive been trying to make this Object move forward on its own and turn left or right in circular fashion if the left/right keys are pressed with unity using C#, this picture will make it clearer: http://prnt.sc/avmxbn
I was only able to make it move on its own and this is my code so far:
using UnityEngine;
using System.Collections;
public class PlayerBehaviour : MonoBehaviour {
Update(){ transform.localPosition += transform.forward *speed *Time.deltaTime
float speed = 5.0f;
// Use this for initialization
void Start () {
Debug.Log ("it's working?");
}
// Update is called once per frame
void Update () {
transform.localPosition += transform.forward * speed * Time.deltaTime;
}
void FixedUpdate(){
}
}
I have no idea, however, how to change left or right directions in circular paths like the picture linked demonstrates. Anyone able to help me? Thank you.
There are obvious errors in your code. You call Update() twice. The first time without a return type. You shouldn't do that. Start by deleting the first Update() and the code on the same line.
Then to answer your question you will have to look into getting input from the user. Use Input.GetKey() and pass it a KeyCode value such as KeyCode.Afor the 'A' key. So you can say:
if(Input.GetKey(KeyCode.A))
{
//do something(for example, Turn the player right.)
}
Then look into rotating the object using transform.Roate to rotate the player.
Attach this script to your moving object:
using UnityEngine;
public class MoveController : MonoBehaviour {
float angle = 1F;
float speed = 0.2F;
void Update ()
{
if ( Input.GetKey (KeyCode.LeftArrow) )
transform.Rotate(Vector3.up, -angle);
else if( Input.GetKey (KeyCode.RightArrow) )
transform.Rotate(Vector3.up, angle);
transform.Translate(Vector3.forward * speed);
}
}
The key point here is to separate your moving from your rotating functionality.
You can use this script for movement :
using UnityEngine;
public class MovementController : MonoBehaviour {
public Rigidbody rigidbody;
float angle = 0f;
const float SPEED = 1f;
float multiplier = 1f;
void FixedUpdate(){
if ( Input.GetKey (KeyCode.LeftArrow) )
angle -= Time.deltaTime * SPEED * multiplier;
else if( Input.GetKey (KeyCode.RightArrow) )
angle += Time.deltaTime * SPEED * multiplier;
rigidbody.velocity = new Vector2(Mathf.Sin(angle) * SPEED, Mathf.Cos(angle) * SPEED);
}
}
Multiplier value is inversely proportional to the radius.

Categories