I want to move my camera detached from player, but it should have the same speed as the player. If the player is not in the camera´s visible area, the player should die.
I´ve already done player death if it is not in camera area.
Vague question, with a vague answer:
Add a script like this on the camera object:
float speed = ??;
GameObject player;
void Update() {
var step = speed * Time.deltaTime
transform.position = Vector3.MoveTowards(transform.position, player.position, step)
}
and of course, instantiate the player variable in the Start function :)
Related
I wrote this code for player movement:
public float gravity = -9.8f;
Vector3 movement = new Vector3(deltaX, 0, deltaZ);
movement = Vector3.ClampMagnitude(movement, speed);
movement.y = gravity;
The gravity variable is supposed to keep the Player to the ground but the problem is that it also slowly slides the player around the terrain.
Setting Horizontal Only look to the Player and Vertical Only look to the Camera in the Unity Editor solves the problem.
I attach a movement script to the player. with reference to the roller ball tutorial and modified it for jump. the problem is that when may player moves in any direction the player starts to rotate in that direction and even if i am standing still at the one position it starts to rotate and fall down the platform. the player has a rigidbody, boxcollider components.
void Awake ()
{
playerRigidbody = GetComponent<Rigidbody>();
Coll = GetComponent<CapsuleCollider>();
}
/*private void Update()
{
}*/
// Update is called once per frame
void FixedUpdate ()
{
float h = Input.GetAxisRaw("Horizontal");
float v = Input.GetAxisRaw("Vertical");
bool down = Input.GetKeyDown(KeyCode.Space);
if (down)
{
playerRigidbody.AddForce(Vector3.up * jumpForce, ForceMode.Impulse);
}
Move(h, v);
}
private bool IsGrounded()
{
return Physics.CheckCapsule(Coll.bounds.center, new Vector3(Coll.bounds.center.x,Coll.bounds.min.y,Coll.bounds.center.z),Coll.height * 9f,Ground);
}
void Move (float h, float v)
{
movement.Set(h, 0f, v);
movement = movement.normalized * speed * Time.deltaTime;
playerRigidbody.MovePosition(transform.position + movement);
}
In your code,you use AddForce function,so I confirm your player rigidbody doesn't set Kinematic to true.
When your charactor collision with any other objects ,such as ground,wall, your charactor maybe rotate.
You could freeze rigidbody's rotation via inspector like Bijan says.
I don't recommand your use AddForce and MovePosition together.It may has other problem.
like this
This is due to the nature of the Rigidbody component. This component is very lifelike and when force is added and removed, the object still has inertia and therefore the object is still moving.
When it comes to the rotation it is due to the fact that when a force is applied to an object, the object also acquires rotational motion (also known as angular motion).
You can freeze the rotation using the constraints on the Rigidbody component.
Have a deeper look into this component [here].1
In my opinion, it is one of the core components of Unity and it is definitely worth looking into.
I hope I answered your question!
I'm building a top down shooter and so I have my camera above my player and the map. Here's the code I've written in the player controller script for movement:
public class playerMovement : MonoBehaviour {
public float speed;
private Camera mainCamera;
void Start () {
mainCamera = FindObjectOfType<Camera>();
}
// Update is called once per frame
void Update () {
// player movement
transform.Translate(speed * Input.GetAxis("Horizontal") * Time.deltaTime, 0f, speed * Input.GetAxis("Vertical") * Time.deltaTime);
// Camera Ray casting
Ray cameraRay = mainCamera.ScreenPointToRay(Input.mousePosition);
Plane groundPlane = new Plane(Vector3.up, Vector3.zero);
float rayLength;
if (groundPlane.Raycast(cameraRay, out rayLength)) {
Vector3 look = cameraRay.GetPoint(rayLength);
Debug.DrawLine(cameraRay.origin, look, Color.red);
transform.LookAt(new Vector3(look.x, transform.position.y, look.z));
}
}
}
I want to be able to move the player using the WASD keys and also rotate following the direction on where the mouse is, however I don't want the rotation of the player to change the direction of the keys, I need the player to move forwards if the W key is pressed no matter which way the player is facing.
However for some reason my code makes the player move forwards depending on which way it is facing which I don't want.
How can I fix this?
The problem is that your transform.Translate call is in "self" space. Forward, backward, left, right are all relative to the direction the transform is facing. That is why your player is moving relative to the facing direction.
If you want to translate relative to "global" or "world" space, you have to add an additional parameter.
// player movement
transform.Translate(speed * Input.GetAxis("Horizontal") * Time.deltaTime,
0f,
speed * Input.GetAxis("Vertical") * Time.deltaTime,
Space.World);
Note the Space.World parameter at the end, to set the world coordinate system.
You can find more in the Unity docs here: https://docs.unity3d.com/ScriptReference/Transform.Translate.html
You need to look at the difference between local and global coordinate systems.
Right now your WASD keys are moving the player character according to global coordinates, and you want the WASD movement to be dependant on the player's orientation so you need to use a local coordinate system.
http://wiki.unity3d.com/index.php?title=Converting_Between_Coordinate_Systems
I have a blockbreaker type game coded using C# that mainly works fine but upon play testing i have found the ball will slow right down in certain situations! i.e if it wedges between to game object bricks the force of the ball rapidly slows down! 8 times out of ten this will not happen but other times it does and im unsure why! i will post the Ball script i think you will need to help solve this but should you need anymore information then please ask.
public class Ball : MonoBehaviour {
private Paddle paddle;
private bool hasStarted = false;
private Vector3 paddleToBallVector;
void Start () {
paddle = GameObject.FindObjectOfType<Paddle> ();
paddleToBallVector = this.transform.position - paddle.transform.position;
}
// Update is called once per frame
void Update () {
if (!hasStarted) {
//lock ball relative to the paddle
this.transform.position = paddle.transform.position + paddleToBallVector;
//wait for mouse press to start
if (Input.GetMouseButtonDown (0)) {
//if (Input.GetTouch(0).phase == TouchPhase.Ended){
hasStarted = true;
this.GetComponent<Rigidbody2D> ().velocity = new Vector2 (2f, 10f);
}
}
}
void OnCollisionEnter2D(Collision2D collision){
Vector2 tweak = new Vector2 (Random.Range(0f,0.2f),Random.Range(0f,0.2f));
if (hasStarted) {
GetComponent<AudioSource> ().Play ();
GetComponent<Rigidbody2D>().velocity += tweak;
}
}
}
You are adding directly to the velocity of the ball. The velocity variable defines a direction and speed, not just a speed as you are thinking here.
So, when the ball collides with a block it has a velocity of (+x, +y). After the collision and bounce is has a velocity of (+x, -y). So by adding a random positive value to the velocity when it has the -y velocity means that it will slow down the ball.
This does not happen every time because you are moving the ball in your Update() method. Change that to 'FixedUpdated()'. Fixed Update handles all physics calculations.
Also, I would recommend having a RigidBody2D on your Ball object. Moving physics objects should always have RigidBodies. With this, you can then use AddForce in the forward direction of your ball and that should solve your problem.
EDIT: I see you have a RigidBody2D already. I missed that the first time. Instead of having GetComponent<RigidBody2D>().velocity try GetComponent<RigidBody2D>().AddForce( transform.forward * impulseAmount, ForceMode.Impluse );
Working on a multiplayer game in Unity3D. Like many others, I've got some serious issues getting the camera to follow the player. In a normal game, you simply make the camera object a child of the player object to make it follow the player. In multiplayer, this is not an option as players need to spawn (prefab).
So instead you need to use C# to make the camera follow the player using the player objects transform position. This is what I've tried:
public Transform target;
public float smoothing = 5f;
Vector3 offset;
public GameObject playerPrefab;
private void SpawnPlayer()
{
Network.Instantiate(playerPrefab, Vector3.up * 5, Quaternion.identity, 0);
offset = transform.position - target.position;
}
void LateUpdate()
{
Vector3 targetCamPos = target.position + offset;
transform.position = Vector3.Lerp(transform.position, targetCamPos, smoothing * Time.deltaTime);
}
Ofcourse I've assigned the player prefab to target. So when the game starts, the cameras position is transformed to the players position. But after that, it refuses to follow the player. It just sits there.
So I've started debugging this with:
Debug.log(target.position);
It returns the starting location of the player, but doesn't get updated as the player moves around. It remains the same. So that's obviously the reason the camera won't follow the player.
The question is: Why doesn't the player position get updated? Or most likely it does, but the script doesn't see it. What am I doing wrong?
According to your comments,here is your problem.
When you drag the prefab you assign the transform of the prefab. The player is actually an instance of the prefab (a clone) but not the prefab itself.
You need to create the new object and assign its transform to it.
GameObject player = (GameObject)Network.Instantiate(playerPrefab, Vector3.up * 5, Quaternion.identity, 0);
target = player.transform;
offset = transform.position - target.position;