I've applied this standard assets script to my camera for a 2D game and it's actually doing a good job but since my background texture is placed inside a quad that "follows" the player and not the camera at higher movement speed the camera gets too far or too much behind the player and gets out of view.
Since I never programmed in JS I'd like to ask you how should I tweak this code to stop the script from moving the camera if the velocity is over (for example) 5f.
I tried to change it this way :
var target : Transform;
var smoothTime = 0.3;
private var thisTransform : Transform;
private var velocity : Vector2;
function Start()
{
thisTransform = transform;
}
function Update()
{
if(velocity.x > 5f) //in C# I'd do it this way, but apparently
velocity.x = 5f; //this is not stopping the camera from getting out of game-sight
thisTransform.position.x = Mathf.SmoothDamp( thisTransform.position.x,
target.position.x, velocity.x, smoothTime);
thisTransform.position.y = Mathf.SmoothDamp( thisTransform.position.y,
target.position.y, velocity.y, smoothTime);
}
This possibly happens because i'm actually passing a reference as a parameter (velocity.x called as a reference http://docs.unity3d.com/Documentation/ScriptReference/Mathf.SmoothDamp.html)
I am not sure if I understand you correctly.
If you want to set your camera's max speed, Mathf.SmoothDamp() can set maxSpeed.
var maxSpeed : float = 5.0f;
Mathf.SmoothDamp(transform.position.x, target.position.x, velocity.x, smoothTime, maxSpeed);
Related
I'm struggling a lot with moving Rigidbodies, currently I have this method to move player:
private void SimpleMove()
{
var scaledMovementSpeed = movementSpeed;
_isRunning = false;
if (Run)
{
scaledMovementSpeed *= runMultiplier;
_isRunning = true;
}
var trans = transform;
var forward = trans.forward;
var newDirection = Vector3.RotateTowards(forward, SimpleMoveVector, Time.fixedDeltaTime * rotationSpeed, 0.0f);
trans.rotation = Quaternion.LookRotation(newDirection, trans.up);
var velocity = _rigidbody.velocity;
var velocityChange = new Vector3(forward.x * scaledMovementSpeed, velocity.y, forward.z * scaledMovementSpeed) - velocity;
_rigidbody.AddForce(velocityChange, ForceMode.VelocityChange);
_isMoving = true;
}
Map is build out of simple cubes right now and the player has capsule collider on him with freeze rotation on all axes.
By tweaking force values a little bit I managed to get it to work properly without the need to check for collisions myself but
expected behavior of player going diagonally into wall is to slide perpendicular to its surface. When I get close to cube's corner character slides across but when I'm going diagonally into a wall character just stops. Haven't tried it with analog input yet.
Is there a way to properly make character slide (fe. put proper physics material on him, or the wall?) or do I need to explicitly check and manage these collisions myself for that?
I thought that my turn-and-then-go-forward method might be messing with proper colliding, but I made the turn instant and the behavior was exactly the same.
I have a GameObject that takes position coordinates from a file. This GameObject moves with vibration rather than smoothly. (as if moving back and forth.)
Here is the code that provides the movement:
int counter = 0;
void Update()
{
var maxDistance = speed_* Time.deltaTime;
var oldPosition = transform.position;
var newPosition = Vector3.MoveTowards(transform.position, positions[counter], maxDistance);
var actualDistance = Vector3.Distance(newPosition, oldPosition);
var distanceRemainder = maxDistance - actualDistance;
if (distanceRemainder > 0.0001)
{
newPosition = Vector3.MoveTowards(newPosition, positions[counter], distanceRemainder);
counter++;
}
transform.localPosition = newPosition;
}
NOTE: The data read from the file is in the "positions" array (x,y,z coordinates).
When I lower the 300f value in the variable maxDistance, the vibration stops and the motion becomes more fluid. However, Gameobject speed is also slowing down. How can I ensure a fast and smooth movement?
SOLUTION:
While looking for a solution of the problem, I came across the this topic. It helped me learn the source of the problem.
I have observed that the GameObject is not vibrating in Scene view, it was moving smoothly. But the object seemed to be vibrating in GameView. The problem is not the moving object, it's the camera function I write to follow it.
The camera function that was written to follow the object has been updated and the problem has disappeared.
One can see more of the solution by going to Post #13 in the link above.
Thanks to everyone trying to help.
This is caused cause you are using your distanceRemainder as your maxDistanceDelta, which I think is incorrect, if you want a smooth movement, you should multiply it for the Time.deltaTime, try:
newPosition = Vector3.MoveTowards(newPosition, positions[counter], distanceRemainder*Time.deltaTime);
Or simply declare speed variable and do:
newPosition = Vector3.MoveTowards(newPosition, positions[counter], speed*Time.deltaTime);
I assume what you want is your object moving with a constant speed to the first position. Once it reaches it, move to the next one.
I would do it in a simple Coroutine which is better to understand and maintain than doing stuff in Update:
private void Start()
{
// todo assign positions
StartCoroutine(RunPositions());
}
private IEnumerator RunPositions()
{
foreach(var position in positions)
{
while(!Mathf.Approximately(Vector3.Distance(transform.position, position), 0))
{
var maxDistance = speed_* Time.deltaTime;
transform.position = Vector3.MoveTowards(transform.position, positions[counter], maxDistance);
// render and continue in the next frame
yield return null;
}
}
}
If you are fine with a precision of 0.00001 you can also simply use
while(transform.position != position)
instead.
I'm coming across a roadblock on something I thought would be a relatively simple problem. I want to "roll" the camera on the z-axis by pressing the "Q" and "E" keys.
Here is the code I've written, which is attached to my camera object:
#pragma strict
var keyboardSensitivity : float = 10.0f;
private var rotZ : float;
private var localRotation : Quaternion;
function Start () {
rotZ = 0.0f;
}
function Update () {
if(Input.GetKey(KeyCode.Q)) {
rotZ += Time.deltaTime * keyboardSensitivity;
localRotation = Quaternion.Euler(0.0f, 0.0f, rotZ);
transform.rotation = localRotation;
}
if(Input.GetKey(KeyCode.E)) {
rotZ -= Time.deltaTime * keyboardSensitivity;
localRotation = Quaternion.Euler(0.0f, 0.0f, rotZ);
transform.rotation = localRotation;
}
}
Based on my knowledge, this should be all that is needed. But when I hit the Q or E keys, absolutely nothing happens. Why?
Nothing happens because your code is likely not attached to the camera or it is attached to another GameObject. It cannot be attached to another GameObject. It has to be attached to the camera since you are referencing transform.rotation which will affect the current GameObject the script is attached to.
Select your camera then drag the script to it. Click "Play" and press the Q or E button. The camera should rotate. I really do recommend Unity project tutorials to you.
I make a character move on the surface of a circle. I let the camera move and rotate follow character. But the camera move and rotate very jerky. If I increase the value of the third parameter, the shock increases. and to reduce the value of the third parameter, the camera does not rotate to keep up the character. Help me fix it
My Code Camera Follow Player
public class CameraFollow : MonoBehaviour
{
public Transform player;
GameController gc;
public float speed = 2;
Vector3 pos = new Vector3 (0, 0, -10);
// Use this for initialization
void Start ()
{
gc = FindObjectOfType (typeof(GameController)) as GameController;
}
void FixedUpdate ()
{
if (gc.gameState == GameController.GameState.playing || gc.gameState == GameController.GameState.changeWave) {
transform.position = player.position + pos;
transform.rotation = Quaternion.Slerp (transform.rotation,
player.transform.rotation,
speed * Time.deltaTime);
}
}
}
Setting the position of a transform inside of FixedUpdate is a red flag for sure, especially when you're reporting that it's "jerky". Fixed update happens at an irregular interval compared to the frames displayed. This is because Physics needs to update using a fixed time step. The reason why this is the case is out of scope for this question.
Long story short, try changing FixedUpdate to Update and that should fix things looking "jerky".
Let me know if this doesn't work and I'll look for other possible causes.
If you are using a Rigidbody2D to move the character, make sure to set its Interpolate property to 'Interpolate'. This should fix it.
Using Unity3d First Person Controller, I want the player to move forward automatically in the direction the camera is looking at. It should behave the same as using the arrow keys, except I keep the arrow up key "pressed". I have this working in the script below, however the player slows down as he rotates the first-person camera away from the 0 degrees on the y-axis. When looking towards the 0 degrees on the y-axis, player speed is normal again.
How can I modify the script below so that the player always moves at a constant speed, no matter the camera rotation?
I set this script on the First Person Controller parent node:
public var head : GameObject;
private var motor : CharacterMotor;
// Use this for initialization
function Awake () {
motor = GetComponent(CharacterMotor);
}
// Update is called once per frame
function Update () {
// Retrieve a forward direction based on camera rotation
var directionVector = transform.forward;
directionVector.y = 0;
directionVector.Normalize();
// Apply the direction to the CharacterMotor
motor.inputMoveDirection = transform.rotation * directionVector;
motor.inputJump = Input.GetButton("Jump");
}
// Require a character controller to be attached to the same game object
#script RequireComponent (CharacterMotor)
#script AddComponentMenu ("Character/FPS Input Controller")
Multiply your movement for Time.deltaTime This time is the time between frames.
Example copy from http://docs.unity3d.com/ScriptReference/Time-deltaTime.html
function Update () {
// Move the object 10 meters per second!
var translation : float = Time.deltaTime * 10;
transform.Translate (0, 0, translation);
}