Debug character movement backwards in Unity 5 - c#

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.

Related

How to Rotate 2D Sprite Towards Moving Direction?

I have been searching all day and reading forums but I can't find a way that works. I'm making a top-down view horror game. When my player walks normally he can look around with the cursor in any direction, but when he wants to run he switches to "tank" controls and rotates toward the running direction. I need something like this.
My player movement script so far:
public float walkSpeed;
public float runSpeed;
public float turnSpeed;
private Rigidbody2D rb;
public Camera cam;
private Vector2 moveDirection;
void Start()
{
rb = GetComponent<Rigidbody2D>();
}
void Update()
{
ProcessInput();
}
void FixedUpdate()
{
Move();
}
private void ProcessInput()
{
float moveX = Input.GetAxisRaw("Horizontal");
float moveY = Input.GetAxisRaw("Vertical");
moveDirection = new Vector2(moveX, moveY).normalized;
}
void Move()
{
if (Input.GetKey(KeyCode.LeftShift))
{
//Looking toward movement direction should be applied here
} else {
rb.velocity = new Vector2(moveDirection.x * walkSpeed, moveDirection.y * walkSpeed);
Vector3 mousePosition = cam.ScreenToWorldPoint(Input.mousePosition);
Vector2 direction = mousePosition - transform.position;
float angle = Vector2.SignedAngle(Vector2.right, direction) - 90f;
Vector3 targetRotation = new Vector3(0, 0, angle);
transform.rotation = Quaternion.RotateTowards(transform.rotation, Quaternion.Euler(targetRotation), turnSpeed * Time.deltaTime);
}
}
Any help is greatly appreciated! Thanks in advance!
This problem can be solved by substituting moveDirection instead of the mouse look direction, here it is enough to define a hypothetical variable called direction to detect the correct direction in each of these conditions.
var direction = new Vector2();
var currentSpeed = walkSpeed;
if (Input.GetKey(KeyCode.LeftShift))
{
direction = moveDirection;
currentSpeed = runSpeed;
} else {
direction = cam.ScreenToWorldPoint(Input.mousePosition) - transform.position;
}
var angle = Vector2.SignedAngle(Vector2.right, direction) - 90f;
var targetRotation = new Vector3(0, 0, angle);
var lookTo = Quaternion.Euler(targetRotation);
rb.velocity = new Vector2(moveDirection.x, moveDirection.y) * runSpeed *Time.deltaTime;
transform.rotation = Quaternion.RotateTowards(transform.rotation, lookTo , turnSpeed * Time.deltaTime);

How to make the player move in the direction it is facing

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;
}

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 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