Forum begins after the advertisement:
[Part 17] Question about DEFAULT_MOVESPEED
Home › Forums › Video Game Tutorial Series › Creating a Rogue-like Shoot-em Up in Unity › [Part 17] Question about DEFAULT_MOVESPEED
- This topic has 2 replies, 2 voices, and was last updated 2 weeks, 1 day ago by
Alp Apustaja.
-
AuthorPosts
-
June 26, 2025 at 11:08 am #18386::
using UnityEngine; public class PlayerMovement : MonoBehaviour { [HideInInspector] public float lastHorizontalVector; [HideInInspector] public float lastVerticalVector; [HideInInspector] public Vector2 moveDir; [HideInInspector] public Vector2 lastMovedVector; //References Rigidbody2D rb; PlayerStats player; // Start is called once before the first execution of Update after the MonoBehaviour is created void Start() { player = GetComponent<PlayerStats>(); rb = GetComponent<Rigidbody2D>(); lastMovedVector = new Vector2(1, 0f); //set default for the project to shoot if the character dont move } // Update is called once per frame void Update() { InputManager(); } //frame rate independent void FixedUpdate() { Move(); } //take in the users input void InputManager() { if (GameManager.instance.isGameOver) { return; } float moveX = Input.GetAxisRaw("Horizontal"); float moveY = Input.GetAxis("Vertical"); moveDir = new Vector2(moveX, moveY).normalized; if (moveDir.x != 0) { lastHorizontalVector = moveDir.x; lastMovedVector = new Vector2(lastHorizontalVector, 0f); //last move x } if (moveDir.y != 0) { lastVerticalVector = moveDir.y; lastMovedVector = new Vector2(0f, lastVerticalVector); //last move y } if (moveDir.x != 0 && moveDir.y != 0) { lastMovedVector = new Vector2(lastHorizontalVector, lastVerticalVector); //while moving } } //move the character void Move() { if (GameManager.instance.isGameOver) { return; } rb.linearVelocity = moveDir * DEFAULT_MOVESPEED * player.Stats.moveSpeed; } }
The name ‘DEFAULT_MOVESPEED’ does not exist in the current context. Any Idea why?
June 26, 2025 at 11:16 am #18387::The error you’re encountering, “The name ‘DEFAULT_MOVESPEED’ does not exist in the current context,” indicates that you have not defined a variable or constant named
DEFAULT_MOVESPEED
anywhere in yourPlayerMovement
class or in any accessible scope.To resolve this issue, you need to define
DEFAULT_MOVESPEED
as a field in your class. Here’s how you can do it:- Declare the DEFAULT_MOVESPEED variable: You can declare it as a
float
at the top of yourPlayerMovement
class. You may also want to assign a default value to it.
Here’s an updated version of your code with the
DEFAULT_MOVESPEED
variable added:using UnityEngine; public class PlayerMovement : MonoBehaviour { [HideInInspector] public float lastHorizontalVector; [HideInInspector] public float lastVerticalVector; [HideInInspector] public Vector2 moveDir; [HideInInspector] public Vector2 lastMovedVector; // Constants private const float DEFAULT_MOVESPEED = 5f; // Set your default move speed here // References Rigidbody2D rb; PlayerStats player; // Start is called once before the first execution of Update after the MonoBehaviour is created void Start() { player = GetComponent(); rb = GetComponent(); lastMovedVector = new Vector2(1, 0f); // set default for the project to shoot if the character doesn't move } // Update is called once per frame void Update() { InputManager(); } // Frame rate independent void FixedUpdate() { Move(); } // Take in the user's input void InputManager() { if (GameManager.instance.isGameOver) { return; } float moveX = Input.GetAxisRaw("Horizontal"); float moveY = Input.GetAxis("Vertical"); moveDir = new Vector2(moveX, moveY).normalized; if (moveDir.x != 0) { lastHorizontalVector = moveDir.x; lastMovedVector = new Vector2(lastHorizontalVector, 0f); // last move x } if (moveDir.y != 0) { lastVerticalVector = moveDir.y; lastMovedVector = new Vector2(0f, lastVerticalVector); // last move y } if (moveDir.x != 0 && moveDir.y != 0) { lastMovedVector = new Vector2(lastHorizontalVector, lastVerticalVector); // while moving } } // Move the character void Move() { if (GameManager.instance.isGameOver) { return; } rb.velocity = moveDir * DEFAULT_MOVESPEED * player.Stats.moveSpeed; } }
Key Changes:
- I added a private constant
DEFAULT_MOVESPEED
with a value of5f
. You can adjust this value to fit your game’s design. - I also corrected
rb.linearVelocity
torb.velocity
, which is the correct property to set the Rigidbody’s velocity in Unity.
Make sure to adjust the
DEFAULT_MOVESPEED
value as necessary for your game mechanics!has upvoted this post. June 26, 2025 at 12:17 pm #18388June 26, 2025 at 12:20 pm #18389::Great to hear that the issue is fixed! If you have any more questions or need further assistance with your Unity project or any other coding-related topics, feel free to ask. Happy coding!
June 26, 2025 at 12:29 pm #18390::using Unity.VisualScripting; using UnityEngine; //component that attach to all project prefab [RequireComponent(typeof(Rigidbody2D))] public class Projectile : WeaponEffect { public enum DamageSource { projectile, owner }; public DamageSource damageSource = DamageSource.projectile; public bool hasAutoAim = false; public Vector3 rotationSpeed = new Vector3(0, 0, 0); protected Rigidbody2D rb; protected int piercing; protected virtual void Start() { rb = GetComponent<Rigidbody2D>(); Weapon.Stats stats = weapon.GetStats(); if (rb.bodyType == RigidbodyType2D.Dynamic) { rb.angularVelocity = rotationSpeed.z; rb.linearVelocity = transform.right * stats.speed * weapon.Owner.Stats.speed; } float area = stats.area == 0 ? 1 : stats.area; transform.localScale = new Vector3( area * Mathf.Sign(transform.localScale.x), area * Mathf.Sign(transform.localScale.y), 1 ); piercing = stats.piercing; if (stats.lifespan > 0) Destroy(gameObject, stats.lifespan); if (hasAutoAim) AcquireAutoAimFacing(); } //if projectile have homing, will automatically find a target public virtual void AcquireAutoAimFacing() { float aimAngle; //find all enemies on the screen EnemyStats[] targets = FindObjectsByType<EnemyStats>(FindObjectsInactive.Include, FindObjectsSortMode.None); //select random enemy (if there is 1), otherwise pick random angle if (targets.Length > 0) { EnemyStats selectedTarget = targets[Random.Range(0, targets.Length)]; Vector2 difference = selectedTarget.transform.position - transform.position; aimAngle = Mathf.Atan2(difference.y, difference.x) * Mathf.Rad2Deg; } else { aimAngle = Random.Range(0f, 360f); } transform.rotation = Quaternion.Euler(0, 0, aimAngle); } protected virtual void FixedUpdated() { if (rb.bodyType == RigidbodyType2D.Kinematic) { Weapon.Stats stats = weapon.GetStats(); transform.position += transform.right * stats.speed * Time.fixedDeltaTime; rb.MovePosition(transform.position); transform.Rotate(rotationSpeed * Time.fixedDeltaTime); } } protected virtual void OnTriggerEnter2D(Collider2D other) { EnemyStats es = other.GetComponent<EnemyStats>(); BreakableProps p = other.GetComponent<BreakableProps>(); //only collide with enemies or breakable stuff if (es) { //if there is an owner, and damage source is set to owner, calculate knockback using the owner instead of the projectile Vector3 source = damageSource == DamageSource.owner && owner ? owner.transform.position : transform.position; es.TakeDamage(GetDamage(), source); Weapon.Stats stats = weapon.GetStats(); piercing--; if (stats.hitEffect) { Destroy(Instantiate(stats.hitEffect, transform.position, Quaternion.identity), 5f); } } else if (p) { p.TakeDamage(GetDamage()); piercing--; Weapon.Stats stats = weapon.GetStats(); if (stats.hitEffect) { Destroy(Instantiate(stats.hitEffect, transform.position, Quaternion.identity), 5f); } } if (piercing <= 0) Destroy(gameObject); } }
using UnityEditor.Experimental.GraphView; using UnityEngine; using System.Collections.Generic; using System.Collections; public abstract class Weapon : Item { [System.Serializable] public struct Stats { public string name, description; [Header("Visual")] public Projectile projectilePrefab; public Aura auraPrefab; public ParticleSystem hitEffect; public Rect spawnVariance; [Header("Value")] public float lifespan; public float damage, damageVariance, area, speed, cooldown, projectileInterval, knockback; public int number, piercing, maxInstances; public static Stats operator +(Stats s1, Stats s2) { Stats result = new Stats(); result.name = s2.name ?? s1.name; result.description = s2.description ?? s1.description; result.projectilePrefab = s2.projectilePrefab ?? s1.projectilePrefab; result.auraPrefab = s2.auraPrefab ?? s1.auraPrefab; result.hitEffect = s2.hitEffect == null ? s1.hitEffect : s2.hitEffect; result.spawnVariance = s2.spawnVariance; result.lifespan = s1.lifespan + s2.lifespan; result.damage = s1.damage + s2.damage; result.damageVariance = s1.damageVariance + s2.damageVariance; result.area = s1.area + s2.area; result.speed = s1.speed + s2.speed; result.cooldown = s1.cooldown + s2.cooldown; result.number = s1.number + s2.number; result.piercing = s1.piercing + s2.piercing; result.projectileInterval = s1.projectileInterval + s2.projectileInterval; result.knockback = s1.knockback + s2.knockback; return result; } public float GetDamage() { return damage + Random.Range(0, damageVariance); } } protected Stats currentStats; public WeaponData data; protected float currentCooldown; protected PlayerMovement movement; public virtual void Initialise(WeaponData data) { base.Initialise(data); this.data = data; currentStats = data.baseStats; movement = owner.GetComponent<PlayerMovement>(); currentCooldown = currentStats.cooldown; } protected virtual void Awake() { if (data) currentStats = data.baseStats; } protected virtual void Start() { if (data) { Initialise(data); } } protected virtual void Update() { currentCooldown -= Time.deltaTime; if (currentCooldown <= 0f) { Attack(currentStats.number); } } public override bool DoLevelUp() { base.DoLevelUp(); if (!CanLevelUp()) { Debug.LogWarning(string.Format("cannot level up 0 to level 1, max level 2 already reached", name, currentLevel, data.maxLevel)); } currentStats += data.GetLevelData(++currentLevel); return true; } //check the weapon cooldown is up or not public virtual bool CanAttack() { return currentCooldown <= 0; } protected virtual bool Attack(int attackCount = 1) { if (CanAttack()) { currentCooldown += currentStats.cooldown; return true; } return false; } //get the amount of damage that the weapon supposed to deal and factoring the weapon stat (include damage varaiance, characeter might) for a buff damage public virtual float GetDamage() { return currentStats.GetDamage() * owner.Stats.might; } public virtual Stats GetStats() { return currentStats; } }
‘Weapon’ does not contain a definition for ‘Owner’ and no accessible extension method ‘Owner’ accepting a first argument of type ‘Weapon’ could be found (are you missing a using directive or an assembly reference?)
June 26, 2025 at 12:30 pm #18391::The error occurs because the
Weapon
class inherits from theItem
class, which has theOwner
property. To resolve this, you should use the inheritedOwner
property from the baseItem
class.In the
Weapon
class, replaceweapon.Owner.Stats.speed
withowner.Stats.speed
. This is becauseowner
is already defined in the baseItem
class and is inherited by theWeapon
class.So the line in the
Projectile
class should look like:rb.linearVelocity = transform.right * stats.speed * owner.Stats.speed;
This assumes that
owner
is properly set during the initialization of the weapon, which is typically done in theInitialise
method of theItem
base class.has upvoted this post. - Declare the DEFAULT_MOVESPEED variable: You can declare it as a
-
AuthorPosts
- You must be logged in to reply to this topic.
Advertisement below: