Unity , script to drag camera - c#

I have 2D mesh in the XY plane. I have the following script which moves the camera across the plane, the camera starts at (0,0,-10).
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class DragMap : MonoBehaviour {
private float dist;
private Vector3 MouseStart;
private Vector3 derp;
void Start () {
dist = transform.position.z; // Distance camera is above map
}
void Update () {
if (Input.GetMouseButtonDown (2)) {
MouseStart = new Vector3(Input.mousePosition.x, Input.mousePosition.y, dist);
MouseStart = Camera.main.ScreenToWorldPoint (MouseStart);
MouseStart.z = transform.position.z;
}
else if (Input.GetMouseButton (2)) {
var MouseMove = new Vector3(Input.mousePosition.x, Input.mousePosition.y, dist);
MouseMove = Camera.main.ScreenToWorldPoint (MouseMove);
MouseMove.z = transform.position.z;
transform.position = transform.position - (MouseMove - MouseStart);
}
}
}
But I cannot for the life of me figure out what to change so that if I drag my mouse to the right, the camera goes to the left and vice versa. Similarly if I drag my mouse up I want to move the camera down and vice versa. Help!
Thank you for any replies.
-DrOmega.

You need to negate the x of the MouseMove vector to only flip the x movement:
MouseMove = new Vector3(-MouseMove.x, MouseMove.y, MouseMove.z);

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class DragMap : MonoBehaviour {
private float dist;
private Vector3 MouseStart;
private Vector3 derp;
void Start () {
dist = transform.position.z; // Distance camera is above map
}
void Update () {
if (Input.GetMouseButtonDown (2)) {
MouseStart = new Vector3(Input.mousePosition.x, Input.mousePosition.y, dist);
MouseStart = Camera.main.ScreenToWorldPoint (MouseStart);
MouseStart.z = transform.position.z;
}
else if (Input.GetMouseButton (2)) {
var MouseMove = new Vector3(Input.mousePosition.x, Input.mousePosition.y, dist);
MouseMove = Camera.main.ScreenToWorldPoint (MouseMove);
MouseMove.z = transform.position.z;
transform.position = transform.position - (MouseMove - MouseStart);
}
}
}
there is an easy fix here. if you want to flip both the x and the y, replace "- (MouseMove - MouseStart)" with "+ (MouseMove - MouseStart)"

Related

How can I make the camera to orbit also up and down?

Should I use Cinemachine for that or it's better to do it with a script from scratch ?
The script is attached to the Main Camera.
Now it's orbit only left right. I want it to orbit 360 degrees with clamp so it wont move down to the floor and to up back.
I should also the Y and not only the X but not sure how.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerFollow : MonoBehaviour {
public Transform PlayerTransform;
private Vector3 _cameraOffset;
[Range(0.01f, 1.0f)]
public float SmoothFactor = 0.5f;
public bool LookAtPlayer = false;
public bool RotateAroundPlayer = true;
public float RotationsSpeed = 5.0f;
// Use this for initialization
void Start () {
_cameraOffset = transform.position - PlayerTransform.position;
}
// LateUpdate is called after Update methods
void LateUpdate () {
if(RotateAroundPlayer)
{
Quaternion camTurnAngle =
Quaternion.AngleAxis(Input.GetAxis("Mouse X") * RotationsSpeed, Vector3.up);
_cameraOffset = camTurnAngle * _cameraOffset;
}
Vector3 newPos = PlayerTransform.position + _cameraOffset;
transform.position = Vector3.Slerp(transform.position, newPos, SmoothFactor);
if (LookAtPlayer || RotateAroundPlayer)
transform.LookAt(PlayerTransform);
}
}

Scripting issue with controlling player in Unity

I am creating a simple 2nd game to learn Unity. I have a script that moves the player left and right on the x axis. Also, I have added mobile tilt controls in the same script. However, I have an issue. When I play the game and press the D key to move the player right, it moves right, but as soon as I let go it jumps back 1/2 way. I've spent hours looking at this code, but the player keeps jumping back to about 1/2 way on the x axis. Why is that? Please help, thank you so much!
using UnityEngine;
using System.Collections;
[System.Serializable]
public class BoundaryOne
{
public float xMin, xMax, yMin, yMax;
}
public class Done_PlayerController : MonoBehaviour
{
public float speed;
public BoundaryOne boundary;
void Update ()
{
transform.Translate(Input.acceleration.x / 4, 0, 0);
}
// void Start ()
//{
//GetComponent<Rigidbody>().velocity = transform.right * speed;
//}
void FixedUpdate ()
{
float moveHorizontal = Input.GetAxis ("Horizontal");
Vector3 movement = new Vector3 (moveHorizontal,0);
GetComponent<Rigidbody>().velocity = movement * speed;
GetComponent<Rigidbody>().position = new Vector3
(
Mathf.Clamp (GetComponent<Rigidbody>().position.x, boundary.xMin, boundary.xMax),
Mathf.Clamp (GetComponent<Rigidbody>().position.y, boundary.yMin, boundary.yMax)
);
}
}
using UnityEngine;
using System.Collections;
[System.Serializable]
public class BoundaryOne
{
public float xMin, xMax, yMin, yMax;
}
public class Done_PlayerController : MonoBehaviour
{
public float speed;
//using mathf to limit bounds of movement
public BoundaryOne boundary;
void Update ()
{
float moveHorizontal = Input.GetAxis("Horizontal");
Vector3 movement = new Vector3(moveHorizontal, 0);
GetComponent<Rigidbody>().velocity = movement * speed;
GetComponent<Rigidbody>().position = new Vector3
(
Mathf.Clamp(GetComponent<Rigidbody>().position.x, boundary.xMin, boundary.xMax),
Mathf.Clamp(0, 0, 0)
);
//my mobile tilt controls
transform.Translate(Input.acceleration.x / 4, 0, 0);
}
// void Start ()
//{
//GetComponent<Rigidbody>().velocity = transform.right * speed;
//}
}

Triggering a script on another object when Clicking and Dragging in Unity

I am doing a 2D project where I've added a sprite as a button to shoot. This button works fine. The script attached is: (I added a box collider to the sprite)
using UnityEngine;
using System.Collections;
public class ClickScript : MonoBehaviour {
public shootTest _shooterScript;
// Use this for initialization
void Start () {
}
void LoadScript()
{
_shooterScript.ShootRock();
}
// Update is called once per frame
void Update () {
if(Input.GetMouseButtonDown(0)){
Vector2 mousePosition = new Vector2();
mousePosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
Collider2D hitCollider = new Collider2D();
hitCollider = this.collider2D;
hitCollider = Physics2D.OverlapPoint(mousePosition);
Debug.Log("mouse pos "+mousePosition.x+" y "+mousePosition.y+" ");
if(hitCollider){
LoadScript();
Debug.Log("Hit "+hitCollider.transform.name+" x"+hitCollider.transform.position.x+" y "+hitCollider.transform.position.y);
}
}
}}
Then I added a crosshair to be able to calculate a direction to aim. Here is the script to click and drag the object. Circle Colider 2D on this object.
using UnityEngine;
using System.Collections;
[RequireComponent(typeof(MeshCollider))]
public class Aim : MonoBehaviour
{
private Vector3 screenPoint;
private Vector3 offset;
void OnMouseDown()
{
screenPoint = Camera.main.WorldToScreenPoint(gameObject.transform.position);
offset = gameObject.transform.position - Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPoint.z));
}
void OnMouseDrag()
{
Vector3 curScreenPoint = new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPoint.z);
Vector3 curPosition = Camera.main.ScreenToWorldPoint(curScreenPoint)+offset;
this.transform.position = curPosition;
}
}
When I add this aiming script and click on the crosshair to drag it, the shoot script goes off.
I'm very new to unity so I'm assuming it is something simple. Thanks for the help.
I changed the update function in the click script to
void Update () {
if(Input.GetMouseButtonDown(0)){
Vector2 mousePosition = new Vector2();
mousePosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
if(this.collider2D.OverlapPoint(mousePosition)){
LoadScript();
}
}
So it only triggers when that specific object is clicked. Maybe there is a cleaner way, but this worked.

Object following Player

I am messing around in Unity and wanted to make a mechanic where a box would touch another object and then that object would follow the Player.
I have Cube set up like this:
And a Sphere with a Box Collider with same options.
My Player script is thus:
public class Player : MonoBehaviour {
public float speed = 0.0f;
public float moveX = 0.0f;
public float moveY = 0.0f;
public GameObject player;
public GameObject obj;
//public float force = 0.0f;
private bool collided = false;
// Use this for initialization
void Start () {
player = GameObject.FindWithTag ("Player");
}
// Update is called once per frame
void FixedUpdate () {
moveX = Input.GetAxis ("Horizontal");
moveY = Input.GetAxis ("Vertical");
player.GetComponent<Rigidbody> ().velocity = new Vector2 (moveX * speed, moveY * speed);
}
void OnCollisionEnter (Collision col) {
if (col.gameObject == obj) {
collided = true;
}
}
void OnCollisionExit (Collision col) {
if (col.gameObject == obj) {
collided = false;
}
}
void Update () {
if(collided) {
obj.transform.position = (player.transform.position - obj.transform.position)*speed;
}
}
}
What have I yet to do? Hoping someone can nudge me in the right direction.
I will provide you two scripts.
1st Script is FollowTarget. This will follow your target forcely.
2nd Script is SmoothFollow which will follow your target in a smooth movement.
FollowTarget.cs
using System;
using UnityEngine;
public class FollowTarget : MonoBehaviour
{
public Transform target;
public Vector3 offset = new Vector3(0f, 7.5f, 0f);
private void LateUpdate()
{
transform.position = target.position + offset;
}
}
SmoothFollow.cs
using UnityEngine;
public class SmoothFollow : MonoBehaviour
{
// The target we are following
[SerializeField]
private Transform target;
// The distance in the x-z plane to the target
[SerializeField]
private float distance = 10.0f;
// the height we want the camera to be above the target
[SerializeField]
private float height = 5.0f;
[SerializeField]
private float rotationDamping;
[SerializeField]
private float heightDamping;
// Use this for initialization
void Start() { }
// Update is called once per frame
void LateUpdate()
{
// Early out if we don't have a target
if (!target)
return;
// Calculate the current rotation angles
var wantedRotationAngle = target.eulerAngles.y;
var wantedHeight = target.position.y + height;
var currentRotationAngle = transform.eulerAngles.y;
var currentHeight = transform.position.y;
// Damp the rotation around the y-axis
currentRotationAngle = Mathf.LerpAngle(currentRotationAngle, wantedRotationAngle, rotationDamping * Time.deltaTime);
// Damp the height
currentHeight = Mathf.Lerp(currentHeight, wantedHeight, heightDamping * Time.deltaTime);
// Convert the angle into a rotation
var currentRotation = Quaternion.Euler(0, currentRotationAngle, 0);
// Set the position of the camera on the x-z plane to:
// distance meters behind the target
transform.position = target.position;
transform.position -= currentRotation * Vector3.forward * distance;
// Set the height of the camera
transform.position = new Vector3(transform.position.x ,currentHeight , transform.position.z);
// Always look at the target
transform.LookAt(target);
}
}
Just choose one of them and then attach it to the gameObject. Like another box that is suppose to follow.
Remove your Update() function in your script as you don't need it anymore.
Also Remove your OnCollisionExit()
void OnCollisionEnter (Collision col) {
if (col.gameObject == obj) {
// If you choose to use SmoothFollow Uncomment this.
//col.GetComponent<SmoothFollow>().target = this.transform;
// If you choose to use FollowTarget Uncomment this
//col.GetComponent<FollowTarget>().target = this.transform;
}
}

How do I make a camera follow an object in unity3d C#?

I have an object called Ball, and I added keyboard interactivity to it(WASD to move the ball)
I need the camera to stay behind and follow the ball, but I am getting errors.
using UnityEngine;
using System.Collections;
public class ballmain : MonoBehaviour {
public bool isMoving = false;
public string direction;
public float camX;
public float camY;
public float camZ;
// Use this for initialization
void Start () {
Debug.Log("Can this run!!!");
}
// Update is called once per frame
void Update () {
camX = rigidbody.transform.position.x -=10;
camY = rigidbody.transform.position.y -=10;
camZ = rigidbody.transform.position.z;
camera.transform.position = new Vector3(camX, camY, camZ);
//followed by code that makes ball move
}
}
I get error "Assets/ballmain.cs(18,44): error CS1612: Cannot modify a value type return value of 'UnityEngine.Transform.position'. Consider storing the value in a temporary variable"
Does anyone know the answer? If I comment out the code about the camera the ball can move around.
here you go . a full code.
Simple Following
using UnityEngine;
using System.Collections;
public class Follow: MonoBehaviour {
public Transform target;
public float smooth= 5.0f;
void Update (){
transform.position = Vector3.Lerp (
transform.position, target.position,
Time.deltaTime * smooth);
}
}
Advanced Following
using UnityEngine;
using System.Collections;
public class SmoothFollowScript: MonoBehaviour {
// The target we are following
public Transform target;
// The distance in the x-z plane to the target
public int distance = 10.0;
// the height we want the camera to be above the target
public int height = 10.0;
// How much we
public heightDamping = 2.0;
public rotationDamping = 0.6;
void LateUpdate (){
// Early out if we don't have a target
if (TargetScript.russ == true){
if (!target)
return;
// Calculate the current rotation angles
wantedRotationAngle = target.eulerAngles.y;
wantedHeight = target.position.y + height;
currentRotationAngle = transform.eulerAngles.y;
currentHeight = transform.position.y;
// Damp the rotation around the y-axis
currentRotationAngle = Mathf.LerpAngle (currentRotationAngle, wantedRotationAngle, rotationDamping * Time.deltaTime);
// Damp the height
currentHeight = Mathf.Lerp (currentHeight, wantedHeight, heightDamping * Time.deltaTime);
// Convert the angle into a rotation
currentRotation = Quaternion.Euler (0, currentRotationAngle, 0);
// Set the position of the camera on the x-z plane to:
// distance meters behind the target
transform.position = target.position;
transform.position -= currentRotation * Vector3.forward * distance;
// Set the height of the camera
transform.position.y = currentHeight;
// Always look at the target
transform.LookAt (target);
}
}
}
If you just simply want to follow the target object align the position of the camera the way you want it and make the camera the child of the target object and the rest will do
Here're one script I found useful during my game development. I didn't create them so I give credit to wiki.unity3d.com for providing this amazing script.
Smooth Follow:
using UnityEngine;
using System.Collections;
public class SmoothFollow2 : MonoBehaviour {
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);
transform.rotation = Quaternion.Slerp (transform.rotation, wantedRotation, Time.deltaTime * rotationDamping);
}
else transform.LookAt (target, target.up);
}
}
More information about my work
Include Standard Mobile Asset to your project. It contains a SmoothFollow2D.js code in its script section. Attach this code with the gameobject and initialize public variables. This will simply do the job for you.
I found this simple and useful unity 2d camera follow script.
using UnityEngine;
using System.Collections;
public class FollowCamera : MonoBehaviour {
public float interpVelocity;
public float minDistance;
public float followDistance;
public GameObject target;
public Vector3 offset;
Vector3 targetPos;
// Use this for initialization
void Start () {
targetPos = transform.position;
}
// Update is called once per frame
void FixedUpdate () {
if (target)
{
Vector3 posNoZ = transform.position;
posNoZ.z = target.transform.position.z;
Vector3 targetDirection = (target.transform.position - posNoZ);
interpVelocity = targetDirection.magnitude * 5f;
targetPos = transform.position + (targetDirection.normalized * interpVelocity * Time.deltaTime);
transform.position = Vector3.Lerp( transform.position, targetPos + offset, 0.25f);
}
}
}
source unity2d camera follow script
The -= in these lines:
camX = rigidbody.transform.position.x -=10;
camY = rigidbody.transform.position.y -=10;
is wrong. The -= will attempt to modify the rigidbody.transform.position. You just want -.
However, as it stands, the camera won't track changes in the target's Z position, nor will it track properly if the camera is rotated. To get the correct position you need (in vectors):-
cam_pos = target_pos - dist_to_target * cam_look_at

Categories

Resources