Changing player direction with keys using C# in Unity - c#

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.

Related

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;

My object begins to spin when collides with the wall

I have in Unity a box that is followed by a camera on a plane. I'm trying to handle the collisions between the box and different objects. When it collides with different things it spins, jumps and happen weird things. I uploaded to YouTube a video to show the problem. The video.
I created an empty that has the camera and the box. This empty has rigidbody of mass 1.
The empty has a script component:
using UnityEngine;
using System.Collections;
public class Character : MonoBehaviour {
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
void OnCollisionEnter(Collision collision)
{
Debug.Log ("Entered OnCollisionEnter function");
if (collision.gameObject.name == "Wall") {
GetComponent<Rigidbody>().velocity = Vector3.zero;
Debug.Log ("Inside if statement");
}
}
}
As you can see I tried to handle the collision writing a code that stops the cube of moving.
Additional information that could help you guys:
The box
It has a box collider. Script:
using UnityEngine;
using System.Collections;
public class MoveCharacter : MonoBehaviour {
public float deltaMovement = 10f;
// Use this for initialization
void Start ()
{
}
// Update is called once per frame
void Update ()
{
Moving();
}
void Moving()
{
//Moves the character to where it needs.
if (Input.GetKey (KeyCode.A)) {
transform.Translate (new Vector3 (-deltaMovement, 0f, 0f) * Time.deltaTime);
} else if (Input.GetKey (KeyCode.D)){
transform.Translate (new Vector3 (deltaMovement, 0f, 0f) * Time.deltaTime);
}
float yRotation = Camera.main.transform.eulerAngles.y;
float movementX = Mathf.Sin ((yRotation * Mathf.PI) / 180) * deltaMovement;
float movementZ = Mathf.Cos ((yRotation * Mathf.PI) / 180) * deltaMovement;
if (Input.GetKey (KeyCode.W)) {
transform.Translate (new Vector3 (movementX, 0f, movementZ) * Time.deltaTime, Space.World);
} else if (Input.GetKey (KeyCode.S)){
transform.Translate (new Vector3 (-movementX, 0f, -movementZ) * Time.deltaTime, Space.World);
}
}
}
The wall
It is a plane with mesh collider and with or without rigidbody didn't make a difference, same problem...
Any help please?
If you are using physics you shouldn't move an object my changing it's translation, you should move it by applying forces to the object, or at least adding a velocity to it. This will allow the physics engine to correctly calculate the reactions with other rigid bodies.
If you move an object my adjusting it's translation then when a collision occurs it will be as though the object has materialised into the other object to the engine as it will be moving with no velocity etc, and you will get weird behaviour.

Using preferred keys to move a player in unity

I am trying to complete roll a ball tutorial (https://unity3d.com/learn/tutorials/projects/roll-ball-tutorial) in a different way by adding two balls.
So two players can play the game.
But the problem i am facing is that i want to configure the preferred keys for the second player like the firsl player uses the traditional arrow keys and the second player use w,a,s,d to move up left down right... my c-sharp code for the first player is this...
using UnityEngine;
using System.Collections;
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); //Values for movement vector 3 takes three arguments like x y z for positions.
rb.AddForce (movement * speed);
}
}
Let me know if anyone have solution
Answered Similar question here.
The easiest solution that will require you not modify your key controls is to not use Input.GetAxis at-all. Detect each key press with Input.GetKey() and their keycodes enum. Problem solved! Now assign the two balls from the Editor. You can easily modify it to work with one ball if that's what you want.
using UnityEngine;
using System.Collections;
public class PlayerController : MonoBehaviour
{
public float speed = 80.0f; // Code for how fast the ball can move. Also it will be public so we can change it inside of Unity itself.
public Rigidbody player1RB; //Player 1 Rigidbody
public Rigidbody player2RB; //Player 2 Rigidbody
//Player 1 Code with aswd keys
void Player1Movement()
{
if (Input.GetKey(KeyCode.A))
{
player1RB.AddForce(Vector3.left * speed);
}
if (Input.GetKey(KeyCode.D))
{
player1RB.AddForce(Vector3.right * speed);
}
if (Input.GetKey(KeyCode.W))
{
player1RB.AddForce(Vector3.forward * speed);
}
if (Input.GetKey(KeyCode.S))
{
player1RB.AddForce(Vector3.back * speed);
}
}
//Player 2 Code with arrow keys
void Player2Movement()
{
if (Input.GetKey(KeyCode.LeftArrow))
{
player2RB.AddForce(Vector3.left * speed);
}
if (Input.GetKey(KeyCode.RightArrow))
{
player2RB.AddForce(Vector3.right * speed);
}
if (Input.GetKey(KeyCode.UpArrow))
{
player2RB.AddForce(Vector3.forward * speed);
}
if (Input.GetKey(KeyCode.DownArrow))
{
player2RB.AddForce(Vector3.back * speed);
}
}
// Update is called once per frame
void FixedUpdate()
{
Player1Movement();
Player2Movement();
}
}
You can define more inputs in edit -> project settings -> Input. To add more inputs just increase the size value and config the new values in. At least input name and keys to the new inputs. Lastly, in your code call the new inputs for player 2 with the names you specified in the project settings.
void FixedUpdate()
{
//float moveHorizontal = Input.GetAxis("Horizontal");
//float moveVertical = Input.GetAxis("Vertical");
// example for player 2
float moveHorizontalPlayer2 = Input.GetAxis("HorizontalPlayer2");
float moveVerticalPlayer2 = Input.GetAxis("VerticalPlayer2");
Vector3 movement = new Vector3 (moveHorizontalPlayer2 , 0.0f, moveVerticalPlayer2 );
rb.AddForce (movement * speed);
}

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.

Unity rotate while moving forward

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.

Categories