Unable to change rotation in Unity3D - unity3d

I've been working on a project in Unity3D and found a javascript that makes the enemies follow the player. This is the script:
var target : Transform; //the enemy's target
var moveSpeed = 3; //move speed
var rotationSpeed = 3; //speed of turning
var myTransform : Transform; //current transform data of this enemy
function Awake()
{
myTransform = transform; //cache transform data for easy access/preformance
}
function Start()
{
target = GameObject.FindWithTag("Player").transform; //target the player
}
function Update () {
//rotate to look at the player
myTransform.rotation = Quaternion.Slerp(myTransform.rotation,
Quaternion.LookRotation(target.position - myTransform.position), rotationSpeed*Time.deltaTime);
//move towards the player
myTransform.position += myTransform.forward * moveSpeed * Time.deltaTime;
}
When the enemies "rotate to look at the player" they rotate from a horizontal position to a vertical. How can I change the script in order to prevent that from happening?

You have a secon parameter at Quaternion.LookRotation
You may use :
Quaternion.LookRotation(target.position - myTransform.position, Vector3.up)
or
Quaternion.LookRotation(target.position - myTransform.position, transform.up)

Related

How to make camera follow to clone player not first production?

I made the code which can follow the clone player in unity. But It worked only the first clone player. If join room second or later, It can't find clone player and doesn't work. How can I fix that ? Thanks for anything your helps.
follow.cs:
private void Awake()
{
mainCam = this;
}
void Start()
{
height = Camera.main.orthographicSize;
width = height * Screen.width / Screen.height;
}
void LateUpdate()
{
if (player == null)
{
player = GameObject.Find("Player(Clone)");
}
else
{
//transform.position = new Vector3(target.position.x, target.position.y, -10f);
transform.position = Vector3.Lerp(transform.position, target.position, Time.deltaTime * speed);
float lx = size.x * 0.5f - width;
float clampX = Mathf.Clamp(transform.position.x, -lx + center.x, lx + center.x);
float ly = size.y * 0.5f - height;
float clampY = Mathf.Clamp(transform.position.y, -ly + center.y, ly + center.y);
transform.position = new Vector3(clampX, clampY, -10f);
}
}
player spawn script:
public void Spawn()
{
GameObject PI = PhotonNetwork.Instantiate("Player", Vector3.zero, Quaternion.identity);
Follow.mainCam.target = PI.transform;
Debug.Log("I'm in the room.");
}
I guess that player stay null, maybe when you are trying to GameObject.Find() by his name, that method returns null.
Maybe you can try it with a tag or use another name?
The simplest solution is to make the camera the child of the player object and then change it's position accordingly through the script
You could also potentially use CineMachine which has some built-in follow methods
In order to change the parent of an object in the hierarchy through code you basically need to do something like this
public Transform camera
public Transform player
camera.parent = player;
and you can then set the camera position like this
camera.position = new Vector3(0, 0, -10);
Since the camera is the child of the player 0, 0, -10 basically means that the camera will be -10 in the Z axis away from the player (which should be behind the player). Whenever the player moves, because the camera is now attached as a child, it will follow the player.

Keep camera from rotating around relative z-axis

I'm trying to create camera movement that mimics the behavior of the unity scene editor where you can perform a spherical rotation around the scene with 2d mouse movement. So far the camera is rotating correctly given x or y movement, but dragging diagonally causes the camera to rotate around its relative z-axis until it gets locked. I cannot force the camera to look at the origin relative to world up because then it cannot rotate upside-down
Here is the script that I've attached to the camera
using UnityEngine;
public class MainCamera : MonoBehaviour
{
Vector2 startingPosition;
Vector2 mousePosition;
Vector3 orthogonalCameraVector;
float degreesPerUnitWidth = 180f / Screen.width;
float degreesPerUnitHeight = 180f / Screen.height;
float cameraRadius = 10;
void Start()
{
transform.position = new Vector3(0, 0, -cameraRadius);
transform.LookAt(Vector3.zero);
orthogonalCameraVector = -Vector3.left;
}
void LateUpdate()
{
if (Input.GetMouseButtonDown(0))
{
mousePosition = Input.mousePosition;
}
if (Input.GetMouseButton(0))
{
var input = new Vector2(Input.mousePosition.x ,Input.mousePosition.y);
startingPosition = mousePosition;
var mouseDelta = startingPosition - input;
var xzDegrees = -mouseDelta.y * degreesPerUnitHeight;
var xzRotation = Quaternion.AngleAxis(xzDegrees, orthogonalCameraVector); // rotate about the relative x-z plane
var yRotation = Quaternion.AngleAxis(-mouseDelta.x * degreesPerUnitWidth, Vector3.up); // rotate about the world y-axis
var rotation = xzRotation * yRotation;
orthogonalCameraVector = rotation * orthogonalCameraVector;
transform.position = rotation * transform.position;
transform.rotation = rotation * transform.rotation;
mousePosition = Input.mousePosition;
}
}
}
I realized the orthogonalCamerVector only needed to be rotated about the y-axis because I wanted to keep it parallel with the xz-plane. I then applied this rotation to the orthogonalCamerVector before rotating the transform so it would always be rotating about a fixed plane so it looks something like this:
var xzDegrees = -mouseDelta.y * degreesPerUnitHeight;
var yRotation = Quaternion.AngleAxis(-mouseDelta.x * degreesPerUnitWidth, Vector3.up); // rotate about the world y-axis
orthogonalCameraVector = yRotation * orthogonalCameraVector;
var xzRotation = Quaternion.AngleAxis(xzDegrees, orthogonalCameraVector); // rotate about the relative x-z plane
var rotation = xzRotation * yRotation;
transform.position = rotation * transform.position;
transform.rotation = rotation * transform.rotation;

Rotate Camera vector to look at player Unity

I create a game, like minigolf/pool. I want to have a camera which follow player.
Position is normally ok, I get the ball direction and I lerp.
Rotation is almost ok. Currently, rotation by Y axis is ok, but camera look straigth forward, and don't look down to the player :
I already try many thing , quaternion angleToaxis, quarternion lookat ... but doesn't look good, the camera go look away ...
Here my code
namespace CameraManagerNameSpace
{
public class CameraManager : MonoBehaviour
{
public float cameraHeight=13f;
public PlayerNameSpace.Player playerToFollow;
public float followSpeed = 3f;
public float rotationSpeed = 1f;
float distance;
Vector3 position;
Vector3 newPos;
Quaternion rotation;
Quaternion newRot;
Vector3 playerPrevPos, playerMoveDir;
bool firstMoveDone=false;
void Start()
{
playerPrevPos = playerToFollow.player_transform.position;
distance = Vector3.Distance(transform.position,playerToFollow.player_transform.position);
}
void FixedUpdate()
{
if(Vector3.Distance(playerToFollow.player_transform.position ,playerPrevPos)>0.5f || firstMoveDone)
{
playerMoveDir = playerToFollow.player_transform.position - playerPrevPos;
firstMoveDone = true;
}
else
{
playerMoveDir = new Vector3(0,0,0);
}
if (playerMoveDir != Vector3.zero)
{
playerMoveDir.Normalize();
newPos = playerToFollow.player_transform.position - playerMoveDir * distance;
newRot =Quaternion.LookRotation(playerMoveDir,Vector3.up);
position = Vector3.Lerp(transform.position, new Vector3(newPos.x,newPos.y+cameraHeight,newPos.z), followSpeed * Time.deltaTime);
rotation = Quaternion.Lerp(transform.rotation, newRot, rotationSpeed * Time.deltaTime);
transform.position = position;
transform.rotation = rotation;
playerPrevPos = playerToFollow.player_transform.position;
}
}
}
}
Also, I don't know why, but after the balls stop the camera continue to do some movement very jerky, jolting, halting.
Well in
newRot = Quaternion.LookRotation(playerMoveDir,Vector3.up);
you are saying the camera to look in the same direction the player is moving ... not to look at the player. This would work if you wouldn't give the camera an extra position offset in the Y axis.
You might want to rather try
// vector pointing from the camera towards the player
var targetDirection = playerToFollow.player_transform.position - transform.position;
newRot = Quaternion.LookRotation(targetDirection, Vector3.up);
You should also rather use Update since FixedUpdate is only used for physics related stuff (also see Update & FixedUpdate)

Rotate object to mouse direction

I have this script, that already works
I,m using leanFinger
var c = Camera.main;
var center = rb.position;
var lastPos = _finger.GetWorldPosition(c.transform.position.y, c);
var lastDelta = Vector3.Distance(center, lastPos);
float angle = Mathf.Atan2(lastPos.x, lastPos.z) * Mathf.Rad2Deg;
rb.rotation = Quaternion.Euler(new Vector3(0, angle - initialRotation, 0));
The problem is that my object is rotating in absolute angles, so if it is already rotated, there is a unwanted rotation. I want it to take an initialRotation value, but i don't know how.
Thanks
You can use transform.rotation to access the current rotation of your object: Transform.rotation
You could also use this method for convenience: Transform.LookAt
Simple JS example:
public var target : Transform;
function Update ()
{
transform.LookAt(target);
}

unity3d: Camera does not follow the player

I am fairly new in game development, I have a piece of code that makes camera move based on player's movement.
player's movement script:
using UnityEngine;
using System.Collections;
public class PlayerMovement : MonoBehaviour
{
public float speed = 6f;
//to store movement
Vector3 movement;
Rigidbody playerRigidbody;
int floorMask;
float camRayLenghth = 100f;
//gets called regardless if the script is enabled or not
void Awake(){
floorMask = LayerMask.GetMask ("Floor");
playerRigidbody = GetComponent<Rigidbody> ();
//Input.ResetInputAxes ();
}
//unity calls automatically on every script and fire any physics object
void FixedUpdate(){
float h = Input.GetAxisRaw ("Horizontal");
float v = Input.GetAxisRaw ("Vertical");
Move (h, v);
//Rotate ();
Turning ();
}
void Move(float h, float v){
movement.Set (h,0f,v);
movement = movement.normalized * speed * Time.deltaTime;
playerRigidbody.MovePosition (transform.position + movement);
}
void Turning (){
Ray camRay = Camera.main.ScreenPointToRay (Input.mousePosition);
RaycastHit floorHit;
if (Physics.Raycast (camRay,out floorHit,camRayLenghth,floorMask)) {
Vector3 playerToMouse = floorHit.point - transform.position;
playerToMouse.y = 0f;
Quaternion newRotation = Quaternion.LookRotation (playerToMouse);
playerRigidbody.MoveRotation (newRotation);
}
}
}
and here is the script attached to the main camera:
using UnityEngine;
using System.Collections;
public class CameraFollow : MonoBehaviour {
// a target for camera to follow
public Transform player;
// how fast the camera moves
public float smoothing = 4f;
//the initial offset from the target
Vector3 offset;
void start(){
//calculation of initial offset (distance) between player and camera
offset = transform.position - player.position;
Debug.Log ("offset is " + offset);
}
void FixedUpdate (){
//updates the position of the camera based on the player's position and offset
Vector3 playerCameraPosition = player.position + offset;
//make an smooth transfer of location of camera using lerp
transform.position = Vector3.Lerp(transform.position, playerCameraPosition, smoothing * Time.deltaTime);
}
}
but when I attach the script to my main camera, as soon as I play test the game camera starts to relocate and moves towards the ground even though the player hasn't moved yet. If I remove the script from the camera and make the camera the child of the player, as soon as I hit play, camera starts to rotate around the object.
Please give me some hints what am I doing wrong ?
The camera offset isn't being set because of the lower case on your start method. This means the offset remains at its default value which is 0,0,0 causing your camera to move to some funky place.
Change: `
void start() {
...
}
to
void Start() {
...
}
see you don't need any code for this just make you camera a child of your player object..
drag you camera object onto the player object in hierarchy