How to make the player move in the direction it is facing - c#

I have this game in unity that is still in development. My movement code so far can move the player with arrow keys. I also have a feature to move the player with your mouse. It turns the player on how it is facing. Let's say the player is facing left. If I click on the up arrow key, it still moves forward. I want to move the player in the direction it is facing.
Code:
using System.Collections.Generic;
using UnityEngine;
public class PlayerMovement : MonoBehaviour {
public float distance = 5f;
public Transform playerCam;
void FixedUpdate () {
transform.localEulerAngles = new Vector3(transform.localEulerAngles.x,
Camera.main.transform.localEulerAngles.y, transform.localEulerAngles.z);
if (Input.GetKey(KeyCode.LeftArrow))
{
Vector3 position = this.transform.position;
position.x--;
this.transform.position = position;
}
if (Input.GetKey(KeyCode.RightArrow))
{
Vector3 position = this.transform.position;
position.x++;
this.transform.position = position;
}
if (Input.GetKey(KeyCode.UpArrow))
{
Vector3 position = this.transform.position;
position.z++;
this.transform.position = position;
}
if (Input.GetKey(KeyCode.DownArrow))
{
Vector3 position = this.transform.position;
position.z--;
this.transform.position = position;
}
if (Input.GetKey("W"))
{
Vector3 position = this.transform.position;
position.z++;
this.transform.position = position;
}
if (Input.GetKey("S"))
{
Vector3 position = this.transform.position;
position.z--;
this.transform.position = position;
}
if (Input.GetKey("A"))
{
Vector3 position = this.transform.position;
position.x--;
this.transform.position = position;
}
if (Input.GetKey("D"))
{
Vector3 position = this.transform.position;
position.x++;
this.transform.position = position;
}
}
}

Use transform.forward to get the direction the player is facing.
It will always be a unit vector, so if you just want to move the position by exactly one unit in the player's forward direction, you can just add it to transform.position:
if (Input.GetKey("W"))
{
this.transform.position += this.transform.forward;
}

Related

Unity Camera Switching Issue?

Hi everyone I'm doing a cannonball mode where players will have a UI panel that looks like a snipe screen. This camera will follow the enemy while in regular play there is another camera for normal play mode( this one stays in place). However when I switch between the two wherever the cannon camera moves when I exit with "E" it stays in that moved position. Is there any way where I can manually revert the position of the camera back in place?
public class CameraFollow : MonoBehaviour
{
public Transform target;
public float smoothSpeed = 0.125f;
public Vector3 offset;
public GameObject scopeOverlay;
public GameObject Camera;
void FixedUpdate ()
{
if (Input.GetKeyDown ("d"))
{
Camera.SetActive (false);
scopeOverlay.SetActive(true);
Vector3 desiredPosition = target.position + offset;
Vector3 smoothedPosition = Vector3.Lerp (transform.position, desiredPosition, smoothSpeed);
transform.position = smoothedPosition;
transform.LookAt (target);
}
if (Input.GetKeyDown ("e"))
{
Camera.SetActive (true);
scopeOverlay.SetActive(false); //To disable it
}
}
}
Save the initial transform values and restore them like so;
private Vector3 initialPosition;
private Quaternion initialRotation;
private void Start ()
{
// Save initial transform values
initialPosition = transform.position;
initialRotation = transform.rotation;
}
void FixedUpdate ()
{
if (Input.GetKeyDown("d"))
{
Camera.SetActive(false);
scopeOverlay.SetActive(true);
Vector3 desiredPosition = target.position + offset;
Vector3 smoothedPosition = Vector3.Lerp(transform.position, desiredPosition, smoothSpeed);
transform.position = smoothedPosition;
transform.LookAt(target);
}
if (Input.GetKeyDown("e"))
{
// Restore transform values
transform.position = initialPosition;
transform.rotation = initialRotation;
Camera.SetActive(true);
scopeOverlay.SetActive(false); //To disable it
}
}

Camera always behind player in Unity3d

I'm struggling with this for quit some time now. I have GameObject, being a sphere, which is my player on a 3d Terrain. I have a Camera which is always on a fixed distance from the player, follows it where it goes with below script:
public GameObject player;
private Vector3 offset;
// Use this for initialization
void Start () {
offset = transform.position - player.transform.position;
}
void LateUpdate () {
transform.position = player.transform.position + offset;
}
So far so good. However what I actually want is that the camera rotates with the player, so it always looks into the direction where the sphere is moving, but always stays behind the player at the same fixed distance, so that the player is always visible in the camera view.
There are a lot of scripts available, but the problem with the onces I've seen so far is that the camera indeed rotate with the player, but because the player actually is a rolling sphere the camera view is rolling and turning as well.
The best script I found so far is below, but this one has the same problem as the other onces, the camera rolls with the player.
public Transform target;
public float distance = 3.0f;
public float height = 3.0f;
public float damping = 5.0f;
public bool smoothRotation = true;
public bool followBehind = true;
public float rotationDamping = 10.0f;
void Update () {
Vector3 wantedPosition;
if(followBehind)
wantedPosition = target.TransformPoint(0, height, -distance);
else
wantedPosition = target.TransformPoint(0, height, distance);
transform.position = Vector3.Lerp (transform.position, wantedPosition, Time.deltaTime * damping);
if (smoothRotation) {
Quaternion wantedRotation = Quaternion.LookRotation(target.position - transform.position, target.up);
//Quaternion ownRotation = Quaternion.RotateTowards;
transform.rotation = Quaternion.Slerp (transform.rotation, wantedRotation, Time.deltaTime * rotationDamping);
}
else transform.LookAt (target, target.up);
}
Can anyone help me with this please?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CameraFollow : MonoBehaviour {
public GameObject player;
public float cameraDistance = 10.0f;
// Use this for initialization
void Start () {
}
void LateUpdate ()
{
transform.position = player.transform.position - player.transform.forward * cameraDistance;
transform.LookAt (player.transform.position);
transform.position = new Vector3 (transform.position.x, transform.position.y + 5, transform.position.z);
}
}
My solution (based on #brennon-provencher answer) with smoothness and auto offset:
public class CameraFollow : MonoBehaviour
{
public GameObject target;
public float speed = 5;
Vector3 offset;
void Start()
{
offset = target.transform.position - transform.position;
}
void LateUpdate()
{
// Look
var newRotation = Quaternion.LookRotation(target.transform.position - transform.position);
transform.rotation = Quaternion.Slerp(transform.rotation, newRotation, speed * Time.deltaTime);
// Move
Vector3 newPosition = target.transform.position - target.transform.forward * offset.z - target.transform.up * offset.y;
transform.position = Vector3.Slerp(transform.position, newPosition, Time.deltaTime * speed);
}
}
You need to move your camera position based on sphere movement direction -
public GameObject player;
private Vector3 offset;
float distance;
Vector3 playerPrevPos, playerMoveDir;
// Use this for initialization
void Start () {
offset = transform.position - player.transform.position;
distance = offset.magnitude;
playerPrevPos = player.transform.position;
}
void LateUpdate () {
playerMoveDir = player.transform.position - playerPrevPos;
playerMoveDir.normalize();
transform.position = player.transform.position - playerMoveDir * distance;
transform.LookAt(player.transform.position);
playerPrevPos = player.transform.position;
}
Edit 2: To fix flickering camera, try this -
void LateUpdate () {
playerMoveDir = player.transform.position - playerPrevPos;
if (playerMoveDir != Vector3.zero)
{
playerMoveDir.normalize();
transform.position = player.transform.position - playerMoveDir * distance;
transform.position.y += 5f; // required height
transform.LookAt(player.transform.position);
playerPrevPos = player.transform.position;
}
}

Move the camera only until a certain position

https://scontent.fmgf1-2.fna.fbcdn.net/v/t34.0-12/15870843_1543174992374352_1359602831_n.gif?oh=dc048c9e04617007c5e82379fd5a9c1a&oe=586CC623
Can you see the blue area in this gif? I want block the camera when the player go more to left, to not see the blue area. This is the code that I'm using to move the camera:
public class configuracoesDaCamera : MonoBehaviour {
Vector3 hit_position = Vector3.zero;
Vector3 current_position = Vector3.zero;
Vector3 camera_position = Vector3.zero;
float z = 0.0f;
public static bool bDedoNoHud;
void Update()
{
if (Input.GetMouseButtonDown(0))
{
hit_position = Input.mousePosition;
camera_position = transform.position;
}
if (Input.GetMouseButton(0))
{
current_position = Input.mousePosition;
LeftMouseDrag();
}
Debug.Log("bDedoNoHud" + bDedoNoHud);
}
void LeftMouseDrag()
{
if (!bDedoNoHud)
{
// From the Unity3D docs: "The z position is in world units from the camera." In my case I'm using the y-axis as height
// with my camera facing back down the y-axis. You can ignore this when the camera is orthograhic.
current_position.z = hit_position.z = camera_position.y;
// Get direction of movement. (Note: Don't normalize, the magnitude of change is going to be Vector3.Distance(current_position-hit_position)
// anyways.
Vector3 direction = Camera.main.ScreenToWorldPoint(current_position) - Camera.main.ScreenToWorldPoint(hit_position);
// Invert direction to that terrain appears to move with the mouse.
direction = direction * -1;
Vector3 position = camera_position + direction;
transform.position = position;
}
}
}
You mean setting up boundaries?
This should help you
Put it in the update()

Debug character movement backwards in Unity 5

I have a character(robot Kyle) and I can move the character from side to side, and forwards. When the character begins to move backwards it disappears for no reason.
Also, how would I move the character in the direction of the mouse? I have it so it faces in direction of the mouse, but the camera angle distorts that a little bit.
using UnityEngine;
using System.Collections;
public class PlayerScript : MonoBehaviour {
public GameControlScript control;
float strafeSpeed = 2;
Animator anim;
bool jumping = false;
void Start () {
anim = GetComponent<Animator>();
}
void Update () {
if (Input.GetKey(KeyCode.RightArrow)){
Vector3 newPosition = this.transform.position;
newPosition.x++;
this.transform.position = newPosition;
}
if (Input.GetKey(KeyCode.LeftArrow)){
Vector3 newPosition = this.transform.position;
newPosition.x--;
this.transform.position = newPosition;
}
if (Input.GetKey(KeyCode.UpArrow)){
Vector3 newPosition = this.transform.position;
newPosition.z++;
this.transform.position = newPosition;
}
if (Input.GetKey(KeyCode.DownArrow)){
Vector3 newPosition = this.transform.position;
newPosition.z--;
this.transform.position -= newPosition;
}
Vector3 mousePos = new Vector3(Input.mousePosition.x, Input.mousePosition.y, 1000);
Vector3 lookPos = Camera.main.ScreenToWorldPoint(mousePos);
lookPos = lookPos - this.transform.position;
float angle = Mathf.Atan2(lookPos.z, lookPos.x) * Mathf.Rad2Deg;
this.transform.rotation = Quaternion.AngleAxis(angle, Vector3.down);
}
void OnTriggerEnter(Collider other)
{
if(other.gameObject.name == "Powerup(Clone)")
{
control.PowerupCollected();
}
else if(other.gameObject.name == "Obstacle(Clone)" &&
jumping == false)
{
control.SlowWorldDown();
}
Destroy(other.gameObject);
}
}
ScreenToWorldPoint may be your problem because you are fixing 1000 as the distance between the camera and your object.
Checkout out this link and try to log your lookPos variable.

Move Camera in UnityScript 2d in C#

I have just started programming Unity 2d, and I have faced one large problem: How do I move the camera? The script is attached to the object "player". I want it to move with the player. Thanks!
/*
I
*/
using UnityEngine;
using System.Collections;
public class PlayerController : MonoBehaviour
{
public float speed = 10; //Float for speed
public string hAxis = "Horizontal";
void Start ()
{
//empty
}
void FixedUpdate ()
{
if (Input.GetAxis (hAxis) < 0) //Left
{
Vector3 newScale = transform.localScale;
newScale.y = 1.0f;
newScale.x = 1.0f;
transform.localScale = newScale;
}
else if (Input.GetAxis (hAxis) > 0) //Right
{
Vector3 newScale =transform.localScale;
newScale.x = 1.0f;
transform.localScale = newScale;
}
//Position transformation
transform.position = transform.position + transform.right * Input.GetAxis(axisName) * speed * Time.deltaTime;
}
}
Without any scripts, you could just drag the Camera GameObject to be a child of the player and the camera would start following the player position.
For a script, try this, set player as the target.
using UnityEngine;
using System.Collections;
public class SmoothCamera2D : MonoBehaviour {
public float dampTime = 0.15f;
private Vector3 velocity = Vector3.zero;
public Transform target;
// Update is called once per frame
void Update ()
{
if (target)
{
Vector3 point = camera.WorldToViewportPoint(target.position);
Vector3 delta = target.position - camera.ViewportToWorldPoint(new Vector3(0.5f, 0.5f, point.z)); //(new Vector3(0.5, 0.5, point.z));
Vector3 destination = transform.position + delta;
transform.position = Vector3.SmoothDamp(transform.position, destination, ref velocity, dampTime);
}
}
}

Categories