not for player movement but I need to network the AI's movement
well I haven't really tried anything because idk how to network movement
Basically you can use one of three approaches.
Easy mode
Add PhotonView and SimpleMode2D to your player
public SimpleMode2D : Monobehaviour {
[SerializeField] private PhotonView view;
[SerializeField] private float speed;
private void Update() {
if(!view.IsMine) return;
float h = Input.GetAxisRaw(“Horizontal”);
float v = Input.GetAxisRaw(“Vertical”);
gameObject.transform.position = new Vector2 (transform.position.x + (h * speed), transform.position.y + (v * speed));
}
RPCMode
You will still need to add PhotonView and RPCPlayer and to your player, but this time your movement control will be separately
public class RPCPlayer : Monobehaviour {
[PunRPC]
private void RPCMove(Vector2 newPosition){
transform.position = newPosition;
}
}
public RPCMode2D : Monobehaviour {
[SerializeField] private PhotonView player;
[SerializeField] private float speed;
private void Update() {
if(!player.IsMine) return;
float h = Input.GetAxisRaw(“Horizontal”);
float v = Input.GetAxisRaw(“Vertical”);
var position = player.transform.position;
player.RPC("RPCMove", new Vector2 (position.x + (h * speed), position.y + (v * speed)));
}
RaiseEvent Mode
Here you will need to create player instantiation/deletion and manipulation. I'm using this method because it more flexible but more complex. You can refer to documentation. Sorry here without code for now, I'll update this comment if you get interested in RaiseEvent usage.
Related
at some point, I want to reset all objects with the PhysicsObject script attached to their first position.
public class PhysicsObjects : MonoBehaviour
{
public float waitOnPickup = 0.1f;
public float breakForce = 35f;
[HideInInspector] public bool pickedUp = false;
[HideInInspector] public Interactions playerInteractions;
Vector3 originalPosition;
Quaternion originalRotation;
public Rigidbody rigidbody;
private void Start()
{
originalPosition = transform.position;
originalRotation = transform.rotation;
}
private void OnCollisionEnter(Collision collision)
{
if (pickedUp)
{
//collision.relativeVelocity.magnitude > breakForce
if (collision.relativeVelocity.magnitude > breakForce)
{
playerInteractions.BreakConnection();
}
}
}
public void ResetObjects()
{
transform.position = originalPosition;
transform.rotation = originalRotation;
if (rigidbody != null)
{
rigidbody.velocity = Vector3.zero;
rigidbody.angularVelocity = Vector3.zero;
}
}
}
and in my other Script:
PhysicsObjects Physics;
private void Start()
{
GameObject inter = GameObject.Find("SeatPillow");
Physics = inter.GetComponent<PhysicsObjects>();
}
....
Physics.ResetObjects();
I tested this only for one object which is SeatPillow and it worked as I specified this object here: GameObject inter = GameObject.Find("SeatPillow");, How would I make this work for all the objects with PhyiscsObject attached without having to specify each one of them?
Create List of PhysicsObjects and populate it when Instantiating desired objects, then use foreach to operate on all of them - physicsObjectsList.ForEach(x => x.Reset());
note: if you are not instantiating those objects from scripts then create public (or [SerializeField] private) list and drug and drop all desired objects from scene to that "other Script" component
I recently started working in Unity. I'm pretty new and have only been working with the software for a day, so I was creating a very basic movement script when an error popped up prompting me to close a curly bracket. I did so, but the error persisted. I think my code is fine, what's going on? I'm sure I'm probably just being an idiot.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Player_Movement : MonoBehaviour {
[SerializeField] private int speed = 10;
[SerializeField] private int jump_height = 200;
[SerializeField] private float m_smoothing = 0.14;
private Vector3 m_Velocity = Vector3.zero;
Rigidbody2D m_Rigidbody;
public void Start()
{
m_Rigidbody = GetComponent<Rigidbody2D>();
}
public void Update()
{
[SerializeField] private float playerInputh = Input.GetAxisRaw("Horizontal");
Vector3 targetVelocity = new Vector2(playerInputh * speed, m_Rigidbody.velocity.y);
m_Rigidbody.velocity = Vector3.SmoothDamp(m_Rigidbody.velocity, targetVelocity, ref m_Velocity, m_smoothing);
if (Input.GetKeyDown("space"))
{
m_Rigidbody.AddForce(new Vector2(0f, jump_height));
}
}
}
The variable "m smoothing" is of type float, and numbers of type float must be accompanied with an f after the end.
For example 5 is of type int or float, 5.0 is of type float and should be written 5.0f, and 0.14 is of type float and should be written 0.14f.
The other problem is that you have entered [SerializeField] private in a method. To declare a local variable, that is, it can be called up only in that method, just write the type and name, and if you want, then assign it a value.
Learn more, because I have simplified some things, but I hope I have been clear.
Here is your error-free code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Player_Movement : MonoBehaviour
{
[SerializeField] private int speed = 10;
[SerializeField] private int jump_height = 200;
[SerializeField] private float m_smoothing = 0.14f;
private Vector3 m_Velocity = Vector3.zero;
Rigidbody2D m_Rigidbody;
public void Start()
{
m_Rigidbody = GetComponent<Rigidbody2D>();
}
public void Update()
{
float playerInputh = Input.GetAxisRaw("Horizontal");
Vector3 targetVelocity = new Vector2(playerInputh * speed, m_Rigidbody.velocity.y);
m_Rigidbody.velocity = Vector3.SmoothDamp(m_Rigidbody.velocity, targetVelocity, ref m_Velocity, m_smoothing);
if (Input.GetKeyDown("space"))
{
m_Rigidbody.AddForce(new Vector2(0f, jump_height));
}
}
}
if you think my answer helped you, you can mark it as accepted. I would very much appreciate it :)
So I'm currently trying to add my player object with it's script into my camera script that is written for camera object.
using UnityEngine;
public class CameraController : MonoBehaviour
{
public Transform target;
private Vector3 offset;
private float damping = 0.2f;
public bool canMove = true;
public PlayerMovement player;
private void Start()
{
player = gameObject.GetComponent<PlayerMovement>();
}
void FixedUpdate()
{
if (player.faceRight)
{
offset = new Vector3(1f, 0.5f, -10f);
transform.position = Vector3.Lerp(transform.position, target.position, damping) + offset;
}
else if (!player.faceRight)
{
offset = new Vector3(-1f, 0.5f, -10f);
transform.position = Vector3.Lerp(transform.position, target.position, damping) + offset;
}
}
}
My problem is that I can't write player = gameObject.Find("Player"); because unity is saying something like "those are different types of elements" but I can drag my player object if I write public PlayerMovement player; and it works. The thing is I want to learn how to use that without dragging my object.
First of all you can expose and assign private (and protected) fields via the Inspector by using the attribute [SerializeField] without being forced to make them public like e.g.
[SerializeField] private PlayerMovement player;
private void Awake()
{
// if it's not referenced via the Inspector
// get it from this object on runtime as fallback
if(!player) player = GetComponent<PlayerMovement>();
}
And then, well, your field player is of type PlayerMovement while Find returns a GameObject → Not the same type.
Now if you want to get that component from the same object this script is attached to .. then why should you use the expensive Find at all?! You already know the object! Use only GetComponent to get the component attached tot he same object as this script (just like in the code above).
If you really want to use Find then you want to use GetComponent on the result, not on gameObject which is the reference to that scripts own GameObject. You would rather do
[SerializeField] private PlayerMovement player;
private void Awake()
{
if(!player) player = GameObject.Find("player").GetComponent<PlayerMovement>();
}
or if there is anyway only one instance of that type in your scene you can also simply use FindObjectOfType
[SerializeField] private PlayerMovement player;
private void Awake()
{
if(!player) player = FindObjectOfType<PlayerMovement>();
}
In general: If you can reference something via the Inspector it is always better doing so. It is way more efficient because the reference will be serialized into your scene or prefab asset so when it is loaded you already "know" the target reference. Using Find is very expensive and even though it was optimized a lot in later versions also GetComponent is work you could be avoiding ;)
I added my both GameObject and PlayerMovement attributes. Wrote gameObject first, which is called as "Player". Then by using my GameObject, I interacted with my script which is called PlayerMovement.
using UnityEngine;
public class CameraController : MonoBehaviour
{
public Transform target;
private Vector3 offset;
private float damping = 0.2f;
public bool canMove = true;
private GameObject playerObject;
private PlayerMovement playerMovementScript;
private void Start()
{
player = GameObject.Find("Player");
player = gameObject.GetComponent<PlayerMovement>();
}
void FixedUpdate()
{
if (player.faceRight)
{
offset = new Vector3(1f, 0.5f, -10f);
transform.position = Vector3.Lerp(transform.position, target.position, damping) + offset;
}
else if (!player.faceRight)
{
offset = new Vector3(-1f, 0.5f, -10f);
transform.position = Vector3.Lerp(transform.position, target.position, damping) + offset;
}
}
}
I fixed that problem when I was writing that issue here. So I'm kinda proud of myself but also I want to share my solution so if anyone encounter a problem like this, they can fix their problems. If anyone has better solution please share.
I am trying to do a 2d game and my object doesn't affect the player's lifebar after they collide. The player's healthbar will will get a bigger lifetime but I think something it's wrong with the scripts. (Also the collider of object that needs to be destroy is "is trigger" checked). I put this PowerUp on the object, and the character script and healthbar script on the player.
Character.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityStandardAssets.CrossPlatformInput;
public class Character : MonoBehaviour
{
Rigidbody2D rb;
float dirX;
[SerializeField]
float moveSpeed = 5f, jumpForce = 600f, bulletSpeed = 500f;
Vector3 localScale;
public Transform barrel;
public Rigidbody2D bullet;
// Use this for initialization
void Start()
{
localScale = transform.localScale;
rb = GetComponent<Rigidbody2D>();
}
// Update is called once per frame
void Update()
{
dirX = CrossPlatformInputManager.GetAxis("Horizontal");
if (CrossPlatformInputManager.GetButtonDown("Jump"))
Jump();
if (CrossPlatformInputManager.GetButtonDown("Fire1"))
Fire();
}
void FixedUpdate()
{
rb.velocity = new Vector2(dirX * moveSpeed, rb.velocity.y);
}
void Jump()
{
if (rb.velocity.y == 0)
rb.AddForce(Vector2.up * jumpForce);
}
void Fire()
{
var firedBullet = Instantiate(bullet, barrel.position, barrel.rotation);
firedBullet.AddForce(barrel.up * bulletSpeed);
}
}
HealthBar.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class HealthBar : MonoBehaviour
{
public Slider slider;
public Gradient gradient;
public Image fill;
public float health = 100;
public void SetMaxHealth(int health)
{
slider.maxValue = health;
slider.value = health;
fill.color = gradient.Evaluate(1f);
}
public void SetHealth(int health)
{
slider.value = health;
fill.color = gradient.Evaluate(slider.normalizedValue);
}
}
PowerUp.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PowerUp : MonoBehaviour
{
public float multiplayer = 1.4f;
public GameObject pickupEffect;
private void OnTriggerEnter(Collider other)
{
if (other.CompareTag("Player"))
{
Pickup(other);
}
}
void Pickup(Collider player)
{
//Spawn a cool effect
Instantiate(pickupEffect, transform.position, transform.rotation);
//Apply effect to the player
HealthBar stats =player.GetComponent<HealthBar>();
stats.health *= multiplayer;
// Remove Effect
Destroy(gameObject);
}
}
First of all as others already mentioned for a 2D game with Rigidbody2D and (hopefully) Collider2D components you want to use OnTriggerEnter2D instead!
The Physics and Physics2D are two completely separated engines and don't know each other. A 3D OnTriggerEnter will never get called for 2D physics events like collisions etc.
Then note that
Also the collider of object that needs to be destroy is "is trigger" checked
this is exactly the wrong way round. If your object shall track a OnTriggerEnter then the one that enters (the player) should have isTrigger enabled! In most cases you don't want to do this because the player shall e.g. actually collide with the floor and not fall through it etc.
So what you would need is rather putting an additional script on the player itself that waits for other trigger objects to enter!
Then to be sure either debug your code line by line or add additional logs in order to see what happens:
PowerUp
// put this on the pickup item
public class PowerUp : MonoBehaviour
{
// Make these private, nobody else needs access to those
// (Encapsulation)
[SerializeField] private float multiplayer = 1.4f;
[SerializeField] private GameObject pickupEffect;
public void Pickup(HealthBar stats)
{
//Spawn a cool effect
Instantiate(pickupEffect, transform.position, transform.rotation);
//Apply effect to the player
stats.health *= multiplayer;
// Remove Effect
Destroy(gameObject);
}
}
PowerUpDetector (on the player)
// put on player!
public class PowerUpDetector : MonoBehaviour
{
// reference this via the Inspector
[SerializeField] private HealthBar healthbar;
private void Awake()
{
if(!healthBar) healthBar = GetComponent<HealthBar>();
}
private void OnTriggerEnter2D(Collider2D other)
{
// or whatever tag your powerups have
if (!other.CompareTag("PowerUp"))
{
Debug.LogWarning($"Registered a collision but with wrong tag: {other.tag}", this);
return;
}
var powerup = other.GetComponent<PowerUp>();
if(!powerup)
{
Debug.LogError($"Object {other.name} is tagged PowerUp but has no PowerUp component attached", this);
return;
}
Debug.Log("Found powerup, pick it up!", this);
powerup.Pickup(healthbar);
}
}
Well, and then what you do is only changing the float value
stats.health *= multiplayer;
but you never update the GUI accordingly like you would do when instead using
stats.SetHealth(stats.health * multiplayer)
(Btw: I think you mean multiplier ;) )
I would suggest to rather implement a property like e.g.
public class HealthBar : MonoBehaviour
{
// Make these private, nobody else needs access to those
// (Encapsulation)
[SerializeField] private Slider slider;
[SerializeField] private Gradient gradient;
[SerializeField] private Image fill;
[SerializeField] private float health = 100;
public float Health
{
get { return health; }
set
{
health = value;
slider.value = health;
fill.color = gradient.Evaluate(slider.normalizedValue);
}
}
// be careful with variable names if you have this name already
// for a class field .. was ok this time but might get confusing
public void SetMaxHealth(int value)
{
slider.maxValue = value;
// The property handles the rest anyway
Health = value;
}
}
so now instead of calling SetHealth you simply assign a new value to Health and its setter is automatically execute as well so your GUI is updated.
public void Pickup(HealthBar stats)
{
//Spawn a cool effect
Instantiate(pickupEffect, transform.position, transform.rotation);
//Apply effect to the player
stats.Health *= multiplayer;
Destroy(gameObject);
}
Your qustions are below,
player will get a bigger lifetime
Also the collider of object that needs to be destroy
What situation possibly you could have
Check your Character is Triggered, so it calls 'OnTriggerEnter' and also check tag.
Check your powerUp item that checked true as trigger, 'isTrigger'
Check if collider or hit object scale is tiny, it won't work with collider.
If you have nothing with above check-list, then it should be working
This is the code. When I try to add the script to the sprite there's the "primary constructor body not allowed" error.
Inside the code editor there are no alerts.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class weapon : MonoBehaviour {
public GameObject dapo;
public float offset;
public Transform mira;
private float tiempo;
public float inicio;
private void Update()
{
Vector3 difference = Camera.main.ScreenToWorldPoint(Input.mousePosition) - transform.position;
float rotZ = Mathf.Atan2(difference.y, difference.x) * Mathf.Rad2Deg;
transform.rotation = Quaternion.Euler(0f, 0f, rotZ + offset);
if (tiempo <= 0)
{
if (Input.GetMouseButtonDown(0))
{
Instantiate(dapo, mira.position, transform.rotation);
tiempo = inicio;
}
}
else
{
tiempo -= Time.deltaTime;
}
}
}